FtpWebRequest 下载文件大小不正确
我正在使用以下代码从远程 ftp 服务器下载文件:
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,我的问题是该进程正在以某种方式更改它。我知道这一点是因为文件大小正在增加。我怀疑这部分代码有问题:
destination.Write(reader.ReadToEnd());
destination.Flush();
任何人都可以提供有关可能出现问题的任何想法吗?
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();
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
StreamReader
和StreamWriter
使用字符数据,因此您将流从字节解码为字符,然后再次将其编码回字节。 dll 文件包含二进制数据,因此这种往返转换会引入错误。您希望直接从responseStream
对象读取字节并写入未包装在StreamWriter
中的FileStream
。如果您使用的是 .NET 4.0,则可以使用
Stream.CopyTo
,但否则您将必须手动复制流。 这个 StackOverflow 问题有一个很好的复制流的方法:
所以,你的代码将如下所示:
StreamReader
andStreamWriter
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 theresponseStream
object and write to aFileStream
that isn't wrapped in aStreamWriter
.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:So, your code will look like this: