2013-12-09 33 views
1

我做在SSH.NET/C#以下非常基本的任務可以從遠程服務器下載文件到本地路徑下載:如何確定文件完成SSH.NET

ConnectionInfo c = new PasswordConnectionInfo(remoteIP, port, username, password); 
var sftp = new SftpClient(c); 
sftp.Connect(); 
using (var stream = new FileStream(destinationFile, FileMode.Create)) 
{ 

//download the file to our local path 
sftp.DownloadFile(fileName, stream); 
stream.Close(); 

} 

sftp.Disconnect(); 

我們確定文件是否完全下載成功,是否只是代碼塊到達stream.Close()?還是有更具體的方法來確定一切是否寫得好?

編輯:This post可能會有所幫助,如果你想看看有多少字節已被下載。它也使一個原始的進度條,這是方便的。我在帖子中測試了代碼,它確實有效。

回答

3

查看SSH.NET的source codeDownloadFile()是一個阻塞操作,直到完全寫入文件纔會返回。

此外,在使用塊內部不需要調用stream.Close(),因爲在退出塊時將廢棄對象。

+0

謝謝!你太棒了! – starmandeluxe

0

當我在使用SSH.NET時,由於某種原因,我不知道或不喜歡.DownloadFile沒有返回值的事實。無論哪種方式,這是我當時的路線。

 StringBuilder sb = new StringBuilder(); 
     ConnectionInfo c = new PasswordConnectionInfo(remoteIP, port, username, password); 
     var sftp = new SftpClient(c); 

     try 
     { 

      using (StreamReader reader = sftp.OpenText(fileName)) 
      { 
       string line; 

       while ((line = reader.ReadLine()) != null) 
       { 
        sb.AppendLine(line); 
       } 

      } 

      File.WriteAllText(destinationFile, sb.ToString()); 

     } 
     catch(Exception ex) 
     { 
      // procress exception 
     }