The underlying connection was closed: An unexpected error occurred on a receive

chat picture chat · May 17, 2009 · Viewed 8.7k times · Source

When I try my program on my win2k8 machine it runs fine but on win 2k3 it gives me this error that error message

here's the code that' generating the error

WebClient wc = new WebClient(); 
wc.DownloadFile("ftp://ftp.website.com/sample.zip");

there's the weird part. if i disable the firewall on the server completely. the error goes away. but it still errors if i add the program to the exception list and turn on the firewall.

have search the web for days, couldn't find any solution.

Answer

Thomas Levesque picture Thomas Levesque · May 17, 2009

You should try using passive mode for FTP. The WebClient class doesn't allow that, but FtpWebRequest does.

FtpWebRequest request = WebRequest.Create("ftp://ftp.website.com/sample.zip") as FtpWebRequest;
request.UsePassive = true;
FtpWebResponse response = request.GetResponse() as FtpWebResponse;
Stream ftpStream = response.GetResponse();
int bufferSize = 8192;
byte[] buffer = new byte[bufferSize];
using (FileStream fileStream = new FileStream("localfile.zip", FileMode.Create, FileAccess.Write))
{
    int nBytes;
    while((nBytes = ftpStream.Read(buffer, 0, bufferSize) > 0)
    {
        fileStream.Write(buffer, 0, nBytes);
    }
}