2016-09-08 28 views
5

używam SSH.NET w C# 2015.SSH.NET Prześlij cały katalog

Dzięki tej metodzie mogę przesłać plik do mojego serwera 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)); 
     } 
    } 
} 

Co działa idealnie dla pojedynczego pliku. Teraz chcę załadować cały folder/katalog.

Czy ktoś teraz, jak to osiągnąć?

Odpowiedz

5

Nie ma magicznej drogi. Musisz wyliczyć pliki i przesłać je jeden po drugim:

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

OK, może możesz podać mi przykład "rekurencji w podkatalogach"? – Francis

+0

Zobacz moją zaktualizowaną odpowiedź. –

+0

Świetne thx za oszczędność czasu. –