我有以下代码用于从服务器下载文件,该文件适用于文本文件。代码取自MSDN样本:
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 :(得分:3)
试试:
request.UseBinary = true;
答案 1 :(得分: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);
}
}