FtpWebRequest Download file Wrong size

Im 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 Im loads is a dll, and my problem is that it is somehow modified by this process. I know this because the file size is increasing. I have a suspicion that this section of code is to blame:

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

Can anyone suggest any ideas as to what might be wrong?

+3
source share
1 answer

StreamReader StreamWriter , . dll , . responseStream FileStream, StreamWriter.

.NET 4.0, Stream.CopyTo, . fooobar.com/questions/15476/... :

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

Source: https://habr.com/ru/post/1753543/


All Articles