2016-09-08 40 views
5

我在C#2015中使用SSH.NET。SSH.NET上傳整個文件夾

使用此方法,我可以上傳文件到我的SFTP服務器。

public void upload() 
{ 
    const int port = 22; 
    const string host = "*****"; 
    const string username = "*****"; 
    const string password = "*****"; 
    const string workingdirectory = "*****"; 
    string uploadfolder = @"C:\test\file.txt"; 

    Console.WriteLine("Creating client and connecting"); 
    using (var client = new SftpClient(host, port, username, password)) 
    { 
     client.Connect(); 
     Console.WriteLine("Connected to {0}", host); 

     client.ChangeDirectory(workingdirectory); 
     Console.WriteLine("Changed directory to {0}", workingdirectory); 

     using (var fileStream = new FileStream(uploadfolder, FileMode.Open)) 
     { 
      Console.WriteLine("Uploading {0} ({1:N0} bytes)", 
           uploadfolder, fileStream.Length); 
      client.BufferSize = 4 * 1024; // bypass Payload error large files 
      client.UploadFile(fileStream, Path.GetFileName(uploadfolder)); 
     } 
    } 
} 

這對於一個單獨的文件完美的作品。現在我想上傳整個文件夾/目錄。

現在有人該怎麼做到這一點?

回答

5

沒有不可思議的方法。你必須列舉這些文件並逐個上傳:

void UploadDirectory(SftpClient client, string localPath, string remotePath) 
{ 
    Console.WriteLine("Uploading directory {0} to {1}", localPath, remotePath); 

    IEnumerable<FileSystemInfo> infos = 
     new DirectoryInfo(localPath).EnumerateFileSystemInfos(); 
    foreach (FileSystemInfo info in infos) 
    { 
     if (info.Attributes.HasFlag(FileAttributes.Directory)) 
     { 
      string subPath = remotePath + "/" + info.Name; 
      if (!client.Exists(subPath)) 
      { 
       client.CreateDirectory(subPath); 
      } 
      UploadDirectory(client, info.FullName, remotePath + "/" + info.Name); 
     } 
     else 
     { 
      using (Stream fileStream = new FileStream(info.FullName, FileMode.Open)) 
      { 
       Console.WriteLine(
        "Uploading {0} ({1:N0} bytes)", 
        info.FullName, ((FileInfo)info).Length); 

       client.UploadFile(fileStream, remotePath + "/" + info.Name); 
      } 
     } 
    } 
} 
+0

好的,也許你可以給我一個關於如何「遞歸到子目錄」的例子嗎? – Francis

+0

查看我的更新回答。 –

+0

節省我的時間很棒thx。 –