使用带SharpSSH的SFTP下载文件夹和子文件夹

时间:2014-07-14 11:28:31

标签: c# directory sftp

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()是用于记录遇到的错误的函数。

尝试生成错误日志但未记录任何错误日志。任何人的想法?

2 个答案:

答案 0 :(得分:1)

我的想法是使用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);
                }
            }
        }
    }
}

答案 1 :(得分:0)

如果以递归方式复制文件和目录,例如'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();