7

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,

MT.
  • 791
  • 5
  • 15
  • 23
  • Are you sure it is not sending the entire 16mb when you close it? Just because you write the data to the stream does not mean it is sent. – Will Dec 16 '10 at 19:27
  • Yep. Can see the file on the ftp server....and have managed to open it. – MT. Dec 17 '10 at 08:34
  • The plot thickens. Carrying this out on my home pc it works... – MT. Dec 17 '10 at 11:52

2 Answers2

5

try

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

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

taken from here

Firo
  • 30,626
  • 4
  • 55
  • 94
0

try to close output before input.

make sure the last buffer isn't to large, or you could write a few empty bytes. I don't know if it's necessary but i always set the request contentlength to the inputfile-length.

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

Wowa
  • 1,791
  • 1
  • 14
  • 24
  • Thanks. Tried that one as well on the offchance, but the same problem. Back to the drawing board... – MT. Dec 16 '10 at 17:31
  • 1
    Try to getresponse and close it: http://sartorialsolutions.wordpress.com/2007/11/27/httpwebrequest-getrequeststream-appeared-to-hang/ – Wowa Dec 17 '10 at 08:50