1. 程式人生 > >使用.NET SFTP 登陸linux上傳下載檔案

使用.NET SFTP 登陸linux上傳下載檔案

1. 從這裡下載
https://github.com/sshnet/SSH.NET

2. 使用wrapper 類

...
public static IList<string> SearchLogs(DateTime fromDate, DateTime toDate)
        {
            var path = Config.LogPath;

            Renci.SshNet.SftpClient sftp = null;
            try
            {
                Console.WriteLine($"trying connect sftp server {Config.IP} with user {Config.UserName}");
                _log.Info($"trying connect sftp server {Config.IP} with user {Config.UserName}");

                sftp = new Renci.SshNet.SftpClient(Config.IP, Config.UserName, Config.Password);
                sftp.Connect();
                Console.WriteLine("sftp connected.");
                _log.Info("sftp connected.");

                var dirs = sftp.ListDirectory(path).ToList();
                var list = new List<string>();
                if (dirs.Count > 0)
                {
                    Console.WriteLine($"{dirs.Count} files detected. downloading.");
                    _log.Info($"{dirs.Count} files detected. downloading.");

                    var tmpPath = MakesureTempFolderCreated();

                    foreach (var sftpFile in dirs)
                    {
                        var ftpFileName = sftpFile.Name;

                        if (!Check(ftpFileName, fromDate, toDate)){
                            continue;
                        }

                        var filePath = Path.Combine(tmpPath, ftpFileName);
                        IfExistThenDelete(filePath);

                        using (var fs = new FileStream(filePath, FileMode.Create))
                        {
                            sftp.DownloadFile(sftpFile.FullName, fs);
                            Console.WriteLine($"file {ftpFileName} has been saved into local path :{filePath} .");
                            _log.Info($"file {ftpFileName} has been saved into local path :{filePath} .");
                        }
                        list.Add(filePath);
                    }
                }
                else
                {
                    Console.WriteLine("No file has been found on SFTP server ");
                }


                Console.WriteLine($"{list.Count} files downloaded from SFTP server [{Config.IP}] ");
                return list;
            }
            catch (Exception ex)
            {
                _log.Error(ex);
                return new List<string>();
            }
            finally
            {
                if (sftp != null)
                {
                    sftp.Disconnect();
                }
            }
        }
...