使用SharpSSH通过SFTP下载文件夹和子文件夹

本文关键字:文件夹 下载 SFTP SharpSSH 通过 使用 | 更新日期: 2023-09-27 18:12:53

sFTP folder structure:
MainFolder
|_FolderA
  |_sub1
    |_file1.txt
  |_sub1
    |_file2.txt  
  .
  .
  .
  |_sub-n
    |_filen.txt     
|_FolderB
  |_sub1
    |_file3.txt
  |_sub1
    |_file4.txt
  .
  .
  .
  |_sub-n
    |_filen.txt   

使用Tamir的dll,可以从sftp下载上述文件夹结构吗?

using Tamir.Sharpssh;
using Tamir.Streams;
try
{
  .
  .
  .
  string[] s = Directory.GetFiles(ftpfolder,"*.txt", SearchOption.AllDirectories);
  for(int i=0; i< s.length; i++)
  {
    osftp.Get(ftpfolder + s[i], localfolder + Path.GetfileName(s.[i]));
  }
}
catch(IOException copyError)
{
   logg(copyerror.message);
}

logg()是一个记录遇到的错误的函数。

尝试生成错误日志,但没有记录。有什么想法吗?

使用SharpSSH通过SFTP下载文件夹和子文件夹

我的想法是使用WinSCP,它有很好的文档和一些很好的例子…SharpSSH很老了,我相信不再维护/过时了…

这是一个用法的例子…

using System;
using WinSCP;
class Example
{
    public static int Main()
    {
        SessionOptions sessionOptions = new SessionOptions
        {
            Protocol = Protocol.Sftp,
            HostName = EdiConfiguration.FtpIpAddressOrHostName,
            UserName = EdiConfiguration.FtpUserName,
            Password = EdiConfiguration.FtpPassword,
            SshHostKeyFingerprint = EdiConfiguration.SshHostKeyFingerprint,
            PortNumber = EdiConfiguration.FtpPortNumber
        };
        using (Session session = new Session())
        {
            session.Open(sessionOptions);
            TransferOptions transferOptions = new TransferOptions();
            transferOptions.TransferMode = TransferMode.Binary;
            transferOptions.ResumeSupport.State = TransferResumeSupportState.Off;
            // Download the files in the OUT directory.
            TransferOperationResult transferOperationResult = session.GetFiles(EdiConfiguration.FtpDirectory, EdiConfiguration.IncommingFilePath, false, transferOptions);
            // Check and throw if there are any errors with the transfer operation.
            transferOperationResult.Check();
            // Remove files that have been downloaded.
            foreach (TransferEventArgs transfer in transferOperationResult.Transfers)
            {
                RemovalOperationResult removalResult = session.RemoveFiles(session.EscapeFileMask(transfer.FileName));
                if (!removalResult.IsSuccess)
                {
                    eventLogUtility.WriteToEventLog("There was an error removing the file: " + transfer.FileName + " from " + sessionOptions.HostName + ".", EventLogEntryType.Error);
                }
            }
        }
    }
}

如果您递归地复制文件和目录,如'scp -r user@host:/dir/on/remote C:'dir'on'local'',您可以这样做。

using Tamir.SharpSsh;
var host = "host address";
var user = @"user account";
var password = @"user password";
var scp = new Scp( host, user, password );
scp.Connect();
scp.Recursive = true;
var remotePath = @"/dir/on/remote";
var localPath = @"C:'dir'on'local'";
scp.Get( remotePath, localPath );
scp.Close();