使用ftp c#异步高效上传多个文件

问题描述 投票:2回答:1

我有这样的场景

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;

这里我使用同步方法在此循环中上传文件。我有一个要求优化此上传。我发现这篇文章How to improve the Performance of FtpWebRequest?并遵循他们提供的说明。因此我达到了2000秒到1000秒的时间。然后我继续使用异步上传,如msdn中的这个例子。 http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest(v=vs.90).aspx。我改变了方法

if (upload using ftp (list.item.fileName)) 

if (aync upload using ftp (list.item.fileName))

但事情变得最糟糕。时间变成1000到4000秒。

我必须将许多文件上传到我的ftp服务器。因此,最好的方法应该是(猜测)异步。有人帮助我以正确的方式做到这一点。我无法找到如何正确使用上面的msdn示例代码。

我的代码 - 同步(删除异常处理以节省空间):

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;  
  }
}

异步方法

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;  
  }
}
c# optimization asynchronous ftp
1个回答
0
投票

你有没有尝试过在你的foreach循环中使用它?

Task.Factory.StartNew(() => UploadFtpFile(folderName, filename));
© www.soinside.com 2019 - 2024. All rights reserved.