Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FTP upload using .NET

I am writing a code to upload a zip file to an ftp server. Surprisingly the code works fine for small files, but with bigger files I end up in problem. I am using Stream object and I have noted that my code is getting stuck while trying to close the Stream (only for big files). The code runs fine if I do not close the Stream (even for big files). Does anyone see any logic in why this is happening. And if I don't close the stream is it possible that I might end up in problem in future.

Code extract:

FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(@"ftp://" + ftpServerIP + @"/" + fileInf.Name));
Stream strm = reqFTP.GetRequestStream();

The code stops responding (when the upload file is big) at:

strm.Close();

There is no exception as this part is within try-catch.

I don't know how to get a stack trace.

like image 330
kobra Avatar asked Feb 16 '10 01:02

kobra


1 Answers

I don't know specifically what error you're getting when closing the stream, but in our application, we do a lot of large file uploads (videos and images). Here's how we write to our FTP stream:

request.KeepAlive = false; // This eliminated some of our stream closing problems

using (Stream stream = request.GetRequestStream())
{
    stream.Write(file.Data, 0, file.Data.Length);
}

I thought that doing a using block would effectively do the Close call on its own, but maybe it also performs other necessary cleanup. Also notice I turned off the FTP keepalives, which caused us problems in some of the third-party FTP sites we uploaded to.

You really should look at the specific exception you're receiving rather than swallowing all exceptions. The error message will most-likely tell you what's wrong. The most common problems we encountered had to do with active vs. passive mode and the keepalives.

Edit:

To discover what was really going on when we had FTP issues with CDNs (and it happens way too frequently), we sometimes had to turn tracing on in our application. See this link for details on how to enable tracing. Another option is to use a tool like Wireshark to sniff the conversation between your application and the FTP server. If you can see what's going in in the FTP protocol, you'll have a much better chance of resolving the issue.

like image 82
Jacob Avatar answered Sep 25 '22 16:09

Jacob