如何使FileSystemWatcher等待提升创建的事件,直到命名目录为止?

时间:2015-06-23 06:53:37

标签: c# events filesystemwatcher

我有FileSystemWatcher,在创建新目录时触发OnCreated事件。但目录名始终是默认名称(newDirectory(1))。

是否有可能等到确认目录名称? (用户焦点离开了ordners名称文本框)

1 个答案:

答案 0 :(得分:0)

你无法直接挂钩文件夹的创建和命名(这显然是两个事件)。相反,您可以创建自己的自定义类,您可以在其中实现目标。以下是示例代码:

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

这个类的用法是这样的:

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

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