I'm setting a file a newName at runtime "rename " context menu strip item clicked and want to FileSystemWatcher.Renamed Event function properly
I'm trying to make File Explorer in c# window form
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}");
}
In renameToolStripMenuItem_Click event OnRenamed event is not running after calling
You're FileSystemWatcher (FSW) is configured correctly, but you're not renaming the file and thereby the FSW isn't raising the OnRename event. Here is a quickly thrown together example that should work:
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
}