2011-12-13 165 views
0

我在ftp服務器中有zip文件,這個zip文件包含多個然後一個xml文件,我想下載這個zip文件並保存到本地磁盤,我寫下面的代碼,我下載文件,但是當我嘗試解壓這個壓縮它把我錯誤文件已損壞......如何從FTP服務器下載ZipFile

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + file); 
request.Method = WebRequestMethods.Ftp.DownloadFile; 
request.Credentials = new NetworkCredential(_remoteUser, _remotePass); 
FtpWebResponse response = (FtpWebResponse)request.GetResponse(); 
Stream responseStream = response.GetResponseStream(); 
StreamReader reader = new StreamReader(responseStream); 

StreamWriter writer = new StreamWriter(destination); 
writer.Write(reader.ReadToEnd()); 

writer.Close(); 
reader.Close(); 
response.Close(); 
+0

你需要告訴我們更多。比如,這是什麼語言? – Almo 2011-12-13 18:59:28

+0

你看過http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.aspx – 2011-12-13 19:04:42

回答

3

您竄通過StreamReader的FTP請求的結果。這對處理字符編碼通常有好處,但是在處理二進制數據(即zip文件)時,您不希望這樣做。相反,您應該直接從流中讀取數據。喜歡的東西:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + file); 
request.Method = WebRequestMethods.Ftp.DownloadFile; 
request.Credentials = new NetworkCredential(_remoteUser, _remotePass); 
FtpWebResponse response = (FtpWebResponse)request.GetResponse(); 
Stream responseStream = response.GetResponseStream(); 

// Copy the data from the responseStream to destination 1k at a time (feel free to increase buffer size) 
byte[] buffer = new byte[1024]; 
for (int amountRead = responseStream.Read(buffer, 0, buffer.Length); amountRead > 0; amountRead = responseStream.Read(buffer, 0, buffer.Length)) 
{ 
    destination.Write(buffer, 0, amountRead); 
} 
destination.Flush(); 

response.Close(); 
1

下面是從FTP服務器下載文件,示例代碼

Uri url = new Uri("ftp://ftp.demo.com/file1.txt"); 
if (url.Scheme == Uri.UriSchemeFtp) 
{ 
    FtpWebRequest objRequest = (FtpWebRequest)FtpWebRequest.Create(url); 
    //Set credentials if required else comment this Credential code 
    NetworkCredential objCredential = new NetworkCredential("FTPUserName", "FTPPassword"); 
    objRequest.Credentials = objCredential; 
    objRequest.Method = WebRequestMethods.Ftp.DownloadFile; 
    FtpWebResponse objResponse = (FtpWebResponse)objRequest.GetResponse(); 
    StreamReader objReader = new StreamReader(objResponse.GetResponseStream()); 
    byte[] buffer = new byte[16 * 1024]; 
    int len = 0; 
    FileStream objFS = new FileStream(Server.MapPath("file1.txt"), FileMode.Create, FileAccess.Write, FileShare.Read); 
    while ((len = objReader.BaseStream.Read(buffer, 0, buffer.Length)) != 0) 
    { 
     objFS.Write(buffer, 0, len); 
    } 
    objFS.Close(); 
    objResponse.Close(); 
}