2016-09-08 10 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)); 
     } 
    } 
} 

これは、1つのファイルに対して完全に機能します。今度はフォルダ/ディレクトリ全体をアップロードしたいと思います。

誰でもこれを達成する方法はありますか?

答えて

5

魔法はありません。ファイルを列挙して1つずつアップロードする必要があります。

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。 –

関連する問題