繁体   English   中英

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

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

我在运行时设置一个文件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事件在调用后未运行

您正确配置了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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM