2

I have the following code that is used to download files from the server, which works for text files. The code is taken from MSDN samples:

public void DownloadFile(string serverPath, string localPath)
        {

            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + serverPath);

                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential(_domain + "\\" + _username, _password);
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream);
                string contents = reader.ReadToEnd();
                File.WriteAllText(localPath, contents);

                reader.Close();
                response.Close();

            }
            catch (WebException ex)
            {                
                string exMsg = string.Empty;


                //add more error codes               
                FtpWebResponse response = (FtpWebResponse)ex.Response;
                MessageBox.Show(response.StatusCode.ToString());

                switch(response.StatusCode) {
                    case  FtpStatusCode.NotLoggedIn:
                        exMsg = "wrong password";
                        break;

                    case FtpStatusCode.ActionNotTakenFileUnavailable:
                        exMsg = "file you are trying to load is not found";
                        break;

                    default:
                        exMsg = "The server is inaccessible or taking too long to respond.";
                        break;
                }   

                throw new Exception(exMsg);
            }

            return;
        }

However, it corrupts dlls and exe. Any ideas what is the culprit here?

sarsnake
  • 26,667
  • 58
  • 180
  • 286

2 Answers2

3

Try that:

request.UseBinary = true;
Max
  • 2,529
  • 1
  • 18
  • 29
2

StreamReader is intended to read text data (it's a TextReader), so using it will corrupt any binary file.

You need to read from the stream directly.

You should be able to do:

Stream responseStream = response.GetResponseStream();

// Don't read/write as text!
// StreamReader reader = new StreamReader(responseStream);
// string contents = reader.ReadToEnd();
//  File.WriteAllText(localPath, contents);

using (var output = File.OpenWrite(localPath))
{
    responseStream.CopyTo(output);
}

Edit:

Since you're using .NET 3.5, you can copy the stream manually:

Stream responseStream = response.GetResponseStream();
using (var output = File.OpenWrite(localPath))
{
    byte[] buffer = new byte[32768];
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write (buffer, 0, read);
    }
}
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373