How to make FileSystemWatcher wait to raise the Created Event until the Directory is named?

375 views Asked by At

I have a FileSystemWatcher which triggers an OnCreated Event when a new Directory is created. But the directories name is always the default name(newDirectory(1)).

Is there a possibility to wait until the directories name is confirmed? (the users focus gets out of the ordners name textbox)

1

There are 1 answers

0
Anjali_RVS On

You cant directly hook both the creation and naming of folder (which is obviously two events). Instead you can create your own customized class in which you can achieve the goal. Here is the sample code:

class FolderCreationWatcher
{
    private FileSystemWatcher watcher = new FileSystemWatcher();
    private string lastFileName = string.Empty;
    public delegate void OnFolderCreated(object sender, FileSystemEventArgs e);
    public event OnFolderCreated FolderCreated;

    Timer timer = new Timer();

    public FolderCreationWatcher(string dirPath, int timeOut)
    {
        watcher.Path = dirPath;
        watcher.EnableRaisingEvents = true;
        watcher.Created += watcher_Created;
        timer.Interval = timeOut;
        timer.Enabled = false;
        timer.Elapsed += timer_Elapsed;
    }

    void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        this.NotifyFolderCreated();
    }

    private void watcher_Created(object sender, FileSystemEventArgs e)
    {
        lastFileName = e.Name;
        watcher.Renamed += OnRenamed;
        timer.Enabled = true;
    }

    void OnRenamed(object sender, RenamedEventArgs e)
    {
        if (e.OldName.Equals(lastFileName))
        {
            lastFileName = e.Name;
            this.NotifyFolderCreated();
        }
    }

    private void NotifyFolderCreated()
    {
        if (FolderCreated != null)
            FolderCreated(this, new FileSystemEventArgs(WatcherChangeTypes.Created, watcher.Path, lastFileName));
        timer.Enabled = false;
        watcher.Renamed -= OnRenamed;
    }

This class usage will be something like this:

FolderCreationWatcher folderWatcher = new FolderCreationWatcher(dirPath, 5000);
        folderWatcher.FolderCreated += OnFolderCreated;

    void OnFolderCreated(object sender, FileSystemEventArgs e)
    {
        //Do Something
    }