denied66
denied66

Reputation: 644

How to tell when a recursive method is finished

While trying to complete a duplicate file software I noticed there was an issue with the Directory.GetDirectories() method. When the folder was not accessible for whatever reason (most of the time it was due to the folder being a system folder) the loop would stop since an exception would be thrown.

After some research trying to figure out what would be the best method to do the recursion manually I found Marc Gravell's example which worked perfectly for my needs.

My issue with the above method is that I can't figure out how it will be possible to know when the recursion method has finished processing any files/folders. So any insights on the matter would be appreciated.

Thanks in advance.

Upvotes: 1

Views: 179

Answers (2)

Jeremy Thompson
Jeremy Thompson

Reputation: 65712

Put a message box after the operation comepletes:

static void Main()
{
  string path = ""; // TODO
  ApplyAllFiles(path, ProcessFile, FolderProcessed);
  MessageBox.Show("Operation complete.");
}

Upvotes: 1

John Wright
John Wright

Reputation: 4607

Can you clarify what you're trying to do?

In the example code provided by Marc, you must provide an Action that will be called for every file discovered, thus the invoking of that action represents the processing of that file.

If you're looking for a way to determine when all of the files and subfolders within a folder have been processed, you'd need to modify the code to add a second action. Something like this:

using System;
using System.IO;
static class Program
{
    static void Main()
    {
        string path = ""; // TODO
        ApplyAllFiles(path, ProcessFile, FolderProcessed);
    }
    static void ProcessFile(string path) {/* ... */}
    static void FolderProcessed(string path) {/* ... */}

    static void ApplyAllFiles(string folder, Action<string> fileAction, Action<string> folderProcessed)
    {
        foreach (string file in Directory.GetFiles(folder))
        {
            fileAction(file);
        }
        foreach (string subDir in Directory.GetDirectories(folder))
        {
            try
            {
                ApplyAllFiles(subDir, fileAction);
            }
            catch
            {
                // swallow, log, whatever
            }
        }

        //**** New action invoked here:
        folderProcessed(folder);
    }
}

Upvotes: 0

Related Questions