0

I have used below code to download file from FTP server to local file system. But When I used this it shows the following error

Exception thrown while running the code

I have used the following code

Code Snippet

private string user = "uname";
private string pass = "passwd";
private FtpWebRequest ftpRequest ;
private FtpWebResponse ftpResponse ;
private Stream ftpStream ;



public void download(string remoteFile, string localFile)
{
    try
    {

        ftpRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://uname:passwd@hostname/foldername/filename");

        ftpRequest.Credentials = new NetworkCredential(user, pass);

        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = false;


        ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;

        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

        ftpStream = ftpResponse.GetResponseStream();

        FileStream localFileStream = new FileStream(localFile, FileMode.Create);

        byte[] byteBuffer = new byte[2048];
        int bytesRead = ftpStream.Read(byteBuffer, 0, 2048);

        try
        {
            while (bytesRead > 0)
            {
                localFileStream.Write(byteBuffer, 0, bytesRead);
                bytesRead = ftpStream.Read(byteBuffer, 0, 2048);
            }
        }
        catch (Exception ex) { Console.WriteLine(ex.ToString()); }

        localFileStream.Close();
        ftpStream.Close();
        ftpResponse.Close();
    }
    catch (Exception ex)
    {

        Console.WriteLine(ex.ToString());
        Console.ReadKey();
    }
    return;
}

Can anyone help me in resolving this?

Update

I have also changed ftpRequest.KeepAlive = false;to ftpRequest.KeepAlive = true;

But I am facing the same exception

wazza
  • 770
  • 5
  • 17
  • 42
  • Refer to this post..it might solve your error. http://stackoverflow.com/questions/9815919/the-underlying-connection-was-closed-the-server-committed-a-protocol-violation – Saravanan Jan 19 '15 at 13:05
  • @Saravanan..thanks for ur post...but when I changed it to true also I am facing the same exception – wazza Jan 19 '15 at 13:07
  • you can also try changing the code by wrapping "ftprequest" with "using". – Saravanan Jan 19 '15 at 13:17

2 Answers2

0

Change ftpRequest.KeepAlive = false; to ftpRequest.KeepAlive = true;

0

When I changed the code as below

 ftpRequest.UsePassive = false;

It downloads the given file from ftp server

wazza
  • 770
  • 5
  • 17
  • 42