2012-09-26 80 views
2

我有以下代碼用於從服務器下載文件,該文件適用於文本文件。代碼取自MSDN示例:ftp損壞的exe和dll文件(C#)

public void DownloadFile(string serverPath, string localPath) 
     { 

      try 
      { 
       FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + serverPath); 

       request.Method = WebRequestMethods.Ftp.DownloadFile; 
       request.Credentials = new NetworkCredential(_domain + "\\" + _username, _password); 
       FtpWebResponse response = (FtpWebResponse)request.GetResponse(); 
       Stream responseStream = response.GetResponseStream(); 
       StreamReader reader = new StreamReader(responseStream); 
       string contents = reader.ReadToEnd(); 
       File.WriteAllText(localPath, contents); 

       reader.Close(); 
       response.Close(); 

      } 
      catch (WebException ex) 
      {     
       string exMsg = string.Empty; 


       //add more error codes    
       FtpWebResponse response = (FtpWebResponse)ex.Response; 
       MessageBox.Show(response.StatusCode.ToString()); 

       switch(response.StatusCode) { 
        case FtpStatusCode.NotLoggedIn: 
         exMsg = "wrong password"; 
         break; 

        case FtpStatusCode.ActionNotTakenFileUnavailable: 
         exMsg = "file you are trying to load is not found"; 
         break; 

        default: 
         exMsg = "The server is inaccessible or taking too long to respond."; 
         break; 
       } 

       throw new Exception(exMsg); 
      } 

      return; 
     } 

但是,它會破壞dll和exe。任何想法是什麼是這裏的罪魁禍首?

+0

可能是編碼在File.WriteAllText中是錯誤的... WriteAllText的默認編碼是utf8 –

回答

2

StreamReader旨在讀取文本數據(它是一個TextReader),所以使用它會破壞任何二進制文件。

您需要直接從流中讀取數據。

你應該能夠做到:

Stream responseStream = response.GetResponseStream(); 

// Don't read/write as text! 
// StreamReader reader = new StreamReader(responseStream); 
// string contents = reader.ReadToEnd(); 
// File.WriteAllText(localPath, contents); 

using (var output = File.OpenWrite(localPath)) 
{ 
    responseStream.CopyTo(output); 
} 

編輯:

由於您使用.NET 3.5,您可以手動複製流:

Stream responseStream = response.GetResponseStream(); 
using (var output = File.OpenWrite(localPath)) 
{ 
    byte[] buffer = new byte[32768]; 
    int read; 
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0) 
    { 
     output.Write (buffer, 0, read); 
    } 
} 
+0

Stream沒有函數CopyTo()。 – sarsnake

+0

@sarsnake它在.NET 4.0+中運行(http://msdn.microsoft.com/zh-cn/library/dd782932.aspx)如果您使用的是3.5或更低版本,請參閱:http://stackoverflow.com/ a/230141/65358 –

+0

我使用3.5,對不起,我會更新問題 – sarsnake

3

試試看:

request.UseBinary = true;