Click here to Skip to main content
15,117,830 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone!

I need some verification on ftp connections. Below is what I have so far to keep the connection alive and open:

C#
FTPWebRequest request = (FtpWebRequest)WebRequest.Create("url");
request.KeepAlive = true;
request.ReadWriteTimeout = 600000;


My goal is to be able to keep the connection open indefinitely until all of the files have been uploaded via FTP successfully. Do I have the code correct? If my goal isn't possible, is the only way to accomplish this to raise the readwritetimeout time very high?

Thanks everyone!
Posted

1 solution

Hello,

FTPWebRequest.KeepAlive property will let you specify a boolean value whether the control connection to the FTP server is closed after the request completes.

FTPWebRequest.ReadWriteTimeout property will let you specify the number of milliseconds before the reading or writing times out. The default value is 300,000 milliseconds (5 minutes).
If your file are very big and/or you have a slow internet connection this can be a problem.

You can try upload the files asynchronously.

Please read the class documentation here.


Sample code to upload a file to a ftp server:
FtpWebRequest ftpRequest;
FtpWebResponse ftpResponse;

try
{
    //Settings required to establish a connection with the server
    this.ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://ServerIP/FileName"));
    this.ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
    this.ftpRequest.Proxy = null;
    this.ftpRequest.UseBinary = true;
    this.ftpRequest.Credentials = new NetworkCredential("UserName", "Password");
    //Selection of file to be uploaded
    FileInfo ff = new FileInfo("File Local Path With File Name");//e.g.: c:\\Test.txt
    byte[] fileContents = new byte[ff.Length];
    //will destroy the object immediately after being used
    using (FileStream fr = ff.OpenRead())
    {
        fr.Read(fileContents, 0, Convert.ToInt32(ff.Length));
    }
    using (Stream writer = ftpRequest.GetRequestStream())
    {
        writer.Write(fileContents, 0, fileContents.Length);
    }
    //Gets the FtpWebResponse of the uploading operation
    this.ftpResponse = (FtpWebResponse)this.ftpRequest.GetResponse(); 
    Response.Write(this.ftpResponse.StatusDescription); //Display response
}
catch (WebException webex)
{
    this.Message = webex.ToString();
}


Cheers,
JAFC
   
Comments
joshrduncan2012 21-Jun-13 16:13pm
   
Thanks JAFC!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900