I have a scenario like this
while ( until toUpload list empty)
{
create ftp folder (list.item);
if (upload using ftp (list.item.fileName))
{
update Uploaded list that successfully updated;
}
}
update database using Uploaded list;
Here I used synchronous method to upload file in this loop. And I got a requirement optimize this upload. I found this article How to improve the Performance of FtpWebRequest? and followed instructions they have provided. Therefore I achieved 2000 seconds to 1000 seconds time. Then I move in to upload using asynchronous as in this example in msdn. http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest(v=vs.90).aspx. I have changed the method
if (upload using ftp (list.item.fileName))
to
if (aync upload using ftp (list.item.fileName))
But the things got worst. time become 1000s to 4000s.
I have to upload many file to my ftp server. Therefore best method should be (guessing) asynchronous. Someone help me how to do this in correct manner. I wasn't able to find how to use above msdn example code correctly.
My code - synchronous (exception handling removed to save space):
public bool UploadFtpFile(string folderName, string fileName)
{
try
{
string absoluteFileName = Path.GetFileName(fileName);
var request = WebRequest.Create(new Uri(
String.Format(@"ftp://{0}/{1}/{2}",
this.FtpServer, folderName, absoluteFileName))) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = true;
request.UsePassive = true;
request.KeepAlive = true;
request.Credentials = this.GetCredentials();
request.ConnectionGroupName = this.ConnectionGroupName;
request.ServicePoint.ConnectionLimit = 8;
using (FileStream fs = File.OpenRead(fileName))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
using(var requestStream = request.GetRequestStream())
{
requestStream.Write(buffer, 0, buffer.Length);
}
}
using (var response = (FtpWebResponse)request.GetResponse())
{
return true;
}
}
catch // real code catches correct exceptions
{
return false;
}
}
async method
public bool UploadFtpFile(string folderName, string fileName)
{
try
{
//this methods is exact method provide in msdn example mail method
AsyncUploadFtp(String.Format(@"ftp://{0}/{1}/{2}",
this.FtpServer, folderName, Path.GetFileName(fileName)), fileName);
return true;
}
catch // real code catches correct exceptions
{
return false;
}
}