FtpWebRequest Download File Incorrect Size

前端 未结 1 849
一整个雨季
一整个雨季 2021-01-20 20:28

I’m using the following code to download a file from a remote ftp server:

        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath);

             


        
相关标签:
1条回答
  • 2021-01-20 21:11

    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.

    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);
    }
    
    0 讨论(0)
提交回复
热议问题