代码之家  ›  专栏  ›  技术社区  ›  Paul Michaels

FtpWebRequest下载文件大小不正确

  •  3
  • Paul Michaels  · 技术社区  · 14 年前

            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();
            }
    

            destination.Write(reader.ReadToEnd());
            destination.Flush();
    

    有人能对可能的错误提出什么看法吗?

    1 回复  |  直到 14 年前
        1
  •  11
  •   Community ahmed    7 年前

    StreamReader StreamWriter 使用字符数据,所以您将流从字节解码为字符,然后再将其编码回字节。dll文件包含二进制数据,因此这种往返转换将引入错误。您想直接从 responseStream 对象并写入 FileStream 流作者

    如果您使用的是.NET4.0,那么 Stream.CopyTo This StackOverflow question 有一个复制流的好方法:

    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);
        }
    }
    

    因此,您的代码如下所示:

    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
    using (Stream responseStream = response.GetResponseStream())
    using (FileStream destination = File.Create(destinationFile))
    {
        CopyStream(responseStream, destination);
    }
    
    推荐文章