在运行时重命名文件编辑名称,FileSystemWatcher.Renamed 事件使用 c# window 形式

Rename a file at runtime edit name , FileSystemWatcher.Renamed Event using c# window form

我在运行时将文件设置为 newName "rename " 单击上下文菜单条项并希望 FileSystemWatcher.Renamed 事件功能正常

我正在尝试以 C# window 形式制作文件资源管理器

 private void renameToolStripMenuItem_Click(object sender, EventArgs e)
    {

        FileSystemWatcher watcher = new FileSystemWatcher(path_textBox.Text);


            //the renaming of files or directories.
            watcher.NotifyFilter = NotifyFilters.LastAccess
                                 | NotifyFilters.LastWrite
                                 | NotifyFilters.FileName
                                 | NotifyFilters.DirectoryName;

            watcher.Renamed += new RenamedEventHandler(OnRenamed);
            watcher.Error += new ErrorEventHandler(OnError);
            watcher.EnableRaisingEvents = true;

    }
    private static void OnRenamed(object source, RenamedEventArgs e)
    {
        //  Show that a file has been renamed.
        WatcherChangeTypes wct = e.ChangeType;
        MessageBox.Show($"File: {e.OldFullPath} renamed to {e.FullPath}");
    }

在renameToolStripMenuItem_Click事件中OnRenamed事件不是运行调用后

您的 FileSystemWatcher (FSW) 配置正确,但您没有重命名文件,因此 FSW 没有引发 OnRename 事件。这是一个应该有效的快速组合示例:

class YourClass
{
    private FileSystemWatcher _watcher;

    // You want to only once initialize the FSW, hence we do it in the Constructor
    public YourClass()
    {    
         _watcher = new FileSystemWatcher(path_textBox.Text);

         //the renaming of files or directories.
         watcher.NotifyFilter = NotifyFilters.LastAccess
                             | NotifyFilters.LastWrite
                             | NotifyFilters.FileName
                             | NotifyFilters.DirectoryName;

         watcher.Renamed += new RenamedEventHandler(OnRenamed);
         watcher.Error += new ErrorEventHandler(OnError);
         watcher.EnableRaisingEvents = true;
    }

    private void renameToolStripMenuItem_Click(object sender, EventArgs e)
    {
        // Replace 'selectedFile' and 'newFilename' with the variables
        // or values you want (probably from the GUI)
        System.IO.File.Move(selectedFile, newFilename);
    }

    private void OnRenamed(object sender, RenamedEventArgs e)
    {
        // Do whatever
        MessageBox.Show($"File: {e.OldFullPath} renamed to {e.FullPath}");
    }

    // Missing the implementation of the OnError event handler
}