FtpWebRequest closing the download stream hangs on large files

I am trying to use FtpWebRequest to upload some files. This works for small files (say 2 MB), but when I try to download a 16 MB file, the files load successfully, but when I call request.GetRequestStream (). Close, the code freezes (or timeout if the timeout is low enough).

I could just a) not close it and b) not bother to get a response from the server, but that doesn't seem right! See the code below (using SSL or not, the same problem occurs).

output.Close () is the string that hangs ....

public static void SendFileViaFtp(string file, string url, bool useSsl, ICredentials credentials) { var request = (FtpWebRequest)WebRequest.Create(url + Path.GetFileName(file)); request.EnableSsl = useSsl; request.UseBinary = true; request.Credentials = credentials; request.Method = WebRequestMethods.Ftp.UploadFile; request.Timeout = 10000000; request.ReadWriteTimeout = 10000000; request.KeepAlive = true; var input = File.Open(file, FileMode.Open); var output = request.GetRequestStream(); var buffer = new byte[1024]; var lastBytesRead = -1; var i = 0; while (lastBytesRead != 0) { i++; lastBytesRead = input.Read(buffer, 0, 1024); Debug.WriteLine(lastBytesRead + " " + i); if (lastBytesRead > 0) { output.Write(buffer, 0, lastBytesRead); }else { Debug.WriteLine("Finished"); } } input.Close(); output.Close(); var response = (FtpWebResponse)request.GetResponse(); response.Close(); } 

Thanks,

+7
source share
2 answers

to try

 // after finished uploading request.Abort(); // <=== MAGIC PART // befor response.Close() var response = (FtpWebResponse)request.GetResponse(); response.Close(); 

taken from here

+5
source

try closing the output before entering.

make sure the last buffer is not big, or you can write some empty bytes. I don't know if this is necessary, but I always set the requestlength of the requestlength to the length of the input file.

Here is a good example: http://dotnet-snippets.de/dns/ftp-file-upload-mit-buffer-SID886.aspx

0
source

All Articles