找到上传时间

时间:2016-01-20 13:45:03

标签: c#

我在文件夹中有几个文件,我想将它们上传到我的服务器。所有文件都在同一时间上传。我想要找到的是当我的服务器上传最后一个文件。我的代码如下:

public void UploadFile()
{   
    // Only get subdirectories that begin with the letter "p."
    string[] dirs = Directory.GetFiles(path+ dataDir);
    int counter = 1;

    foreach (string dir in dirs) {

        try{
            // Get an instance of WebClient
            WebClient client = new System.Net.WebClient();
            //client.UploadProgressChanged += WebClientUploadProgressChanged;
            client.UploadFileCompleted += WebClientUploadCompleted;
            // parse the ftp host and file into a uri path for the upload
            Uri uri = new Uri(m_FtpHost + new FileInfo(dir).Name);
            // set the username and password for the FTP server
            client.Credentials = new System.Net.NetworkCredential(m_FtpUsername, m_FtpPassword);
            // upload the file asynchronously, non-blocking.
            client.UploadFileAsync(uri, "STOR",dir); 
        }
        catch(Exception e){
            print(e.Message);
        }
    }

}

void WebClientUploadCompleted(object sender, UploadFileCompletedEventArgs e)
{
    print( "Upload is finished. ");
}

现在正在为每个文件分别调用UploadFileCompleted但是我希望在上传所有文件时都有一个标志。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

您只需使用私有“totalUploadCounter”var来检查所有上传完成的时间:

private int totalUploadCounter = 0;
private int counter = 0;
public void UploadFile()
{ 
  string[] dirs = Directory.GetFiles(path + dataDir); 
  totalUploadCounter = 0;
  counter = 0;
  foreach (var dir in dirs) {
    totalUploadCounter += Directory.GetFiles(dir).Length;
  }

  // your upload code here
 }

void WebClientUploadCompleted(object sender, UploadFileCompletedEventArgs e)
{
    counter++;
    if (counter == totalUploadCounter) {
      // ALL UPLOADS FINISHED!!!
    }
}