2012-12-05 17 views
0

我編寫了一個程序,用於從遠程FTP站點下載文件並將其保存到本地C盤,然後將該文件上傳到單獨的服務器。現在的問題是,當文件被下載時,它在本地C上創建的文本文件中沒有數據,我無法弄清楚原因。下面是我使用FTP下載不寫入文件中的數據

// Download File 
    public void download(string remoteFile, string localFile) 
    { 

     try 
     { 
      // Create an FTP Request 
      ftpRequest = (FtpWebRequest)FtpWebRequest.Create(downhost + "/" + remoteFile); 
      // Log in to the FTP Server with the User Name and Password Provided 
      ftpRequest.Credentials = new NetworkCredential(downuser, downpass); 
      // When in doubt, use these options 
      ftpRequest.UseBinary = true; 
      ftpRequest.UsePassive = true; 
      ftpRequest.KeepAlive = true; 
      /* Set HTTP Proxy to Null to avoid The Requested FTP Command Is Not Supported When Using HTTP Proxy error */ 
      ftpRequest.Proxy = null; 
      // Specify the Type of FTP Request 
      ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; 
      // Establish Return Communication with the FTP Server 
      ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); 
      // Get the FTP Server's Response Stream 
      ftpStream = ftpResponse.GetResponseStream(); 
      // Open a File Stream to Write the Downloaded File 
      FileStream localFileStream = new FileStream(localFile, FileMode.Create); 
      // Buffer for the Downloaded Data 
      byte[] byteBuffer = new byte[bufferSize]; 
      int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); 
      // Download the File by Writing the Buffered Data Until the Transfer is Complete 

      try 
      { 
       while (bytesRead > 0) 
       { 
        localFileStream.Write(byteBuffer, 0, bytesRead); 
        bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); 
       } 

      } 

      catch (Exception ex) { Console.WriteLine(ex.ToString()); } 
      // Resource Cleanup 
      localFileStream.Close(); 
      ftpStream.Close(); 
      ftpResponse.Close(); 
      ftpRequest = null; 

     } 
     catch (Exception ex) { Console.WriteLine(ex.ToString()); } 
     return; 
    } 

我曾經在http://www.codeproject.com/Tips/443588/Simple-Csharp-FTP-Class找到的代碼爲基礎來構建我關閉程序的代碼,我已經做了谷歌如何其他人都寫他們的ftp下載腳本,但可以搜索沒有找出數據沒有被寫入的原因。

任何幫助表示讚賞。

回答

0

刷新文件。關閉它之前請致電localFileStream.Flush();

+0

補充說,在此行和相同的結果,沒有任何數據文件 //資源清理 localFileStream.Flush()的; localFileStream.Close(); –

+0

你確定FTP流有數據嗎? – Lloyd

+0

是的。我創建了一個用於測試的文件,並確保它有數據。 –

0

我有同樣的方法有問題。我沒有找到一個辦法讓系統正常工作,但我不得不在ftpstream在你的代碼複製到另一個流是這樣的:(在vb.net中,我知道了,我很抱歉)

ftpStream.copyTo(MySecondStream) 
ftpStream.close() 
'do whatever you want with the copy now 
Return MySecondStream 

也許與處理初始流的方式以及保持打開的時間有關。我在這裏發佈我的問題:Why do I have to copy an FTP stream to another variable to return it to the calling method?

0

我在上傳時遇到同樣的問題。寫入0個字節。代碼在一個FTP服務器上工作,但不在另一個上。只是要做到以下幾點:

   client.FtpStream.Flush(); 
       client.FtpStream.Close();