問題描述
我正在使用以下代碼從遠程 ftp 服務器下載文件:
I’m using the following code to download a file from a remote ftp server:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath);
request.KeepAlive = true;
request.UsePassive = true;
request.UseBinary = true;
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(userName, password);
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
using (StreamWriter destination = new StreamWriter(destinationFile))
{
destination.Write(reader.ReadToEnd());
destination.Flush();
}
我正在下載的文件是一個 dll,我的問題是它被這個過程以某種方式改變了.我知道這是因為文件大小在增加.我懷疑這部分代碼有問題:
The file that I’m downloading is a dll and my problem is that it is being altered by this process in some way. I know this because the file size is increasing. I have a suspicion that this section of code is at fault:
destination.Write(reader.ReadToEnd());
destination.Flush();
任何人都可以就可能出現的問題提供任何想法嗎?
Can anyone offer any ideas as to what may be wrong?
推薦答案
StreamReader
和 StreamWriter
處理字符數據,因此您正在將流從字節解碼為字符并然后再次將其編碼回字節.dll 文件包含二進制數據,因此這種往返轉換會引入錯誤.您想直接從 responseStream
對象讀取字節并寫入未包裝在 StreamWriter
中的 FileStream
.
StreamReader
and StreamWriter
work with character data, so you are decoding the stream from bytes to characters and then encoding it back to bytes again. A dll file contains binary data, so this round-trip conversion will introduce errors. You want to read bytes directly from the responseStream
object and write to a FileStream
that isn't wrapped in a StreamWriter
.
如果您使用的是 .NET 4.0,則可以使用 Stream.CopyTo
,否則您將不得不手動復制流.這個StackOverflow問題有一個很好的復制流的方法:
If you are using .NET 4.0 you can use Stream.CopyTo
, but otherwise you will have to copy the stream manually. This StackOverflow question has a good method for copying streams:
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[32768];
while (true)
{
int read = input.Read(buffer, 0, buffer.Length);
if (read <= 0)
return;
output.Write(buffer, 0, read);
}
}
因此,您的代碼將如下所示:
So, your code will look like this:
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (FileStream destination = File.Create(destinationFile))
{
CopyStream(responseStream, destination);
}
這篇關于FtpWebRequest 下載文件大小不正確的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!