-2

I have got several files in folder which I want to upload them to my server. All files are uploaded in the same time. What I want to find is when the last file is uploaded in my server. My code is the following:

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. ");
}

As it is right now UploadFileCompleted is called for every file seperately However I want to have a flag when all files are uploaded. How can I do so?

Thanos Markou
  • 2,587
  • 3
  • 25
  • 32
Jose Ramon
  • 5,572
  • 25
  • 76
  • 152

1 Answers1

1

You can simply use the private "totalUploadCounter" var to check when all uploads are finished:

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!!!
    }
}
sborfedor
  • 316
  • 1
  • 9
  • 24
  • I'm wondering whether this solution has "data race" issue. See here: https://docs.oracle.com/cd/E19205-01/820-0619/geojs/index.html – Christopher Aug 03 '17 at 04:08