1

I am thinking of using following code, but I want to transfer hundreds of files and it does not look viable to connect and then disconnect on every file transfer.

request = (FtpWebRequest) FtpWebRequest.Create(FtpAddress + file);

request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(User, Pass);

request.UsePassive = IsPassive;
request.UseBinary = true;
request.KeepAlive = false;

FileStream fs = File.OpenRead("");
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();

Stream ftpStream = request.GetRequestStream();
ftpStream.Write(buffer, 0, buffer.Length);

ftpStream.Close();

What options do I have for uploading all of these files using a single connection?

Servy
  • 202,030
  • 26
  • 332
  • 449
zish
  • 1,112
  • 1
  • 10
  • 17

1 Answers1

3

I have not verified this to be true, but in my quick 30 second search, if you set

request.KeepAlive = true;

on every request you create except the last one, apparently only the first FTPWebRequest makes a full login connection.

Then when you create the last FTPWebRequest, set

request.KeepAlive = false;

and it will close the connection when done. You can verify this if you have access to the FTP server's logs.

Moose
  • 5,354
  • 3
  • 33
  • 46
  • So this answer was just blindly accepted? It also has multi upvotes?? From everything I have actually tested and tried, the only thing KeepAlive will do is keep the connection open if you close the FtpWebResponse object you create. It would be great to see some code used to achieve the expected results. – Arvo Bowen Oct 27 '15 at 12:02
  • Arvo, this answer/question is more than 4 years old, StackOverflow was somewhat different back then. I just tried to point zish in the right direction, since there were no other answers. It must have worked for them since they accepted the answer. From what you say about KeepAlive, it sounds like what I proposed will work. You create an FTPWebRequest for each file you want to upload, with request.KeepAlive = true, then on the last FTPWebRequest, you set it to false. – Moose Oct 27 '15 at 18:12