2016-11-15 3 views
1

Ich versuche, nur eine Datei mit SSH.NET von einem Server herunterladen.Laden Sie eine bestimmte Datei von SFTP-Server mit SSH.NET

Bisher habe ich dies:

using Renci.SshNet; 
using Renci.SshNet.Common; 
... 
public void DownloadFile(string str_target_dir) 
    { 
     client.Connect(); 
     if (client.IsConnected) 
     { 
      var files = client.ListDirectory(@"/home/xymon/data/hist"); 
      foreach (SftpFile file in files) 
      { 
       if (file.FullName== @"/home/xymon/data/hist/allevents") 
       { 
        using (Stream fileStream = File.OpenWrite(Path.Combine(str_target_dir, file.Name))) 
        { 
         client.DownloadFile(file.FullName, fileStream); 
        } 
       } 
      } 
     } 
     else 
     { 
      throw new SshConnectionException(String.Format("Can not connect to {0}@{1}",username,host)); 
     } 
    } 

Mein Problem ist, dass ich weiß nicht, wie @"/home/xymon/data/hist/allevents" die SftpFile mit dem String zu erstellen.

Das ist der Grund, warum ich die foreach Schleife mit der Bedingung verwenden.

Danke für die Hilfe.

Antwort

3

Sie benötigen keine SftpFile, um SftpClient.DownloadFile aufzurufen. Die Methode verwendet einen einfachen Weg nur:

/// <summary> 
/// Downloads remote file specified by the path into the stream. 
/// </summary> 
public void DownloadFile(string path, Stream output, Action<ulong> downloadCallback = null) 

verwenden Sie es wie:

using (Stream fileStream = File.OpenWrite(Path.Combine(str_target_dir, "allevents"))) 
{ 
    client.DownloadFile("/home/xymon/data/hist/allevents", fileStream); 
} 

Hatten Sie wirklich die SftpFile benötigt, könnten Sie SftpClient.Get Methode verwenden:

/// <summary> 
/// Gets reference to remote file or directory. 
/// </summary> 
public SftpFile Get(string path) 

Aber Sie____ nicht.

-1

Wenn Sie überprüfen wollen, ob die Datei vorhanden ist, können Sie so etwas tun ...

public void DownloadFile(string str_target_dir) 
    { 
     using (var client = new SftpClient(host, user, pass)) 
     { 
      client.Connect(); 
      var file = client.ListDirectory(_pacRemoteDirectory).FirstOrDefault(f => f.Name == "Name"); 
      if (file != null) 
      { 
       using (Stream fileStream = File.OpenWrite(Path.Combine(str_target_dir, file.Name))) 
       { 
        client.DownloadFile(file.FullName, fileStream); 
       } 
      } 
      else 
      { 
       //... 
      } 
     } 
    }