2013-07-30 68 views
1

這使用FTP下載.csv文件。該文件在服務器上爲46k。當我下載時,它被截斷爲44k。我不知道爲什麼......當我在Excel中查看數據時,它被縮短了。我增加了緩衝區到4096但沒有骰子(這可能不是問題)。FTP文件(.csv)下載被截斷

我本來抓住下面的代碼和調整了它:Downloading Files Using FTPWebRequest

讚賞有什麼想法!謝謝。

private void DownloadFile(string userName, string password, string ftpSourceFilePath, string localDestinationFilePath) 
    { 
     int bytesRead = 0; 
     byte[] buffer = new byte[2048];    

     FtpWebRequest request = CreateFtpWebRequest(ftpSourceFilePath, userName, password, false); 
     request.Method = WebRequestMethods.Ftp.DownloadFile; 

     Stream reader = request.GetResponse().GetResponseStream(); 
     FileStream fileStream = new FileStream(localDestinationFilePath, FileMode.Create); 

     while (true) 
     { 
      bytesRead = reader.Read(buffer, 0, buffer.Length);        

      if (bytesRead == 0) 
       break; 

      fileStream.Write(buffer, 0, bytesRead); 
     } 
    } 

    private FtpWebRequest CreateFtpWebRequest(string ftpDirectoryPath, string userName, string password, bool keepAlive) 
    { 
     FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(ftpDirectoryPath)); 

     //Set proxy to null. Under current configuration if this option is not set then the proxy that is used will get an html response from the web content gateway (firewall monitoring system) 
     request.Proxy = null; 

     request.UsePassive = true; 
     request.UseBinary = true; 
     request.KeepAlive = keepAlive; 

     request.Credentials = new NetworkCredential(userName, password); 

     return request; 
    } 
+0

始終使用記事本也看看你的CSV文件,並設置二進制假 – meda

+0

如果你只是while循環後添加fileStream.Close()會發生什麼?或者如果你讓你的緩衝區如此之大以至於整個文件適合一次讀取? – rene

+0

@rene> fileStream.Close()工作!布拉沃......如果可以的話,我會接受你的回答,但我想我們不能接受評論......謝謝! – nanonerd

回答

2

試試這個辦法:

private void DownloadFile(string userName, string password, string ftpSourceFilePath, string localDestinationFilePath) 
{ 
    int Length = 2048; 
    Byte[] buffer = new Byte[Length]; 
    int bytesRead = responseStream.Read(buffer, 0, Length);  

    FtpWebRequest request = CreateFtpWebRequest(ftpSourceFilePath, userName, password, false); 
    request.Method = WebRequestMethods.Ftp.DownloadFile; 

    Stream reader = request.GetResponse().GetResponseStream(); 
    FileStream fileStream = new FileStream(localDestinationFilePath, FileMode.Create); 

    while (bytesRead > 0) 
      { 
     //if (bytesRead == 0) 
      // break; 
       bytesRead = responseStream.Read(buffer, 0, Length); 
       fileStream.Write(buffer, 0, bytesRead); 
      } 

     fileStream.Close(); 
} 
+0

謝謝你。我缺少導致截斷的fileStream.Close()...「while」邏輯實際上可以。 – nanonerd