使用c#窗口窗体在运行时编辑名称,FileSystemWatcher.Renamed事件重命名文件

问题描述 投票:0回答:1

我在运行时设置一个文件newName“重命名”上下文菜单条项目点击并希望FileSystemWatcher.Renamed事件功能正常

我正在尝试以c#窗口形式创建文件资源管理器

 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事件在调用后未运行

c# runtime filesystemwatcher file-rename
1个回答
0
投票

您正确配置了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
}
© www.soinside.com 2019 - 2024. All rights reserved.