Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FtpWebRequest closing the upload stream hangs on large files

Tags:

c#

.net

I am trying to use an FtpWebRequest to upload some files. This works for smallish files (say <2MB), but when I am trying to load a 16MB file, the files uploads successfully, but when I call request.GetRequestStream().Close, the code hangs (or timesout if the timeout is low enough).

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

output.Close() is the line 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,

like image 421
MT. Avatar asked Dec 16 '10 16:12

MT.


1 Answers

try

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

var response = (FtpWebResponse)request.GetResponse();
response.Close();

taken from here

like image 127
Firo Avatar answered Sep 28 '22 05:09

Firo