I am trying to detect when a file is being removed from a folder in my drive. Upon detection, I want to write code that does something. Is there an event handler for this kind of 'event' in C#? Looked around but couldn't find any. Is it even possible?
You can use FileSystemWatcher to monitor a directory, and subscribe to it's Deleted event. See the code below
static void Main(string[] args)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "C:/some/directory/to/watch";
watcher.NotifyFilter = NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.FileName |
NotifyFilters.DirectoryName;
watcher.Filter = "*.*";
watcher.Deleted += new FileSystemEventHandler(OnDeleted);
watcher.EnableRaisingEvents = true;
}
private static void OnDeleted(object sender, FileSystemEventArgs e)
{
throw new NotImplementedException();
}
Related
FileSystemWatcher works if I change the file with notepad.exe, but not if I change the file with VisualStudio. Why?
See also: Powershell File Watcher Not Picking Up File Changes Made in Visual Studio
static void FileWatcher()
{
FileSystemWatcher watcher = new FileSystemWatcher
{
Path = Path.GetDirectoryName(#"D:\Test\"),
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size,
Filter = "file.txt",
EnableRaisingEvents = true
};
watcher.Changed += OnFileChanged;
}
static void OnFileChanged(object sender, FileSystemEventArgs e)
{
Console.WriteLine("{0} Watcher: {1} {2}", DateTime.Now, e.ChangeType, e.FullPath);
}
PS. watcher.Renamed works. Thank you mjwills.
By adding the following lines of code you should be able to capture all events.
watcher.Deleted += OnFileChanged;
watcher.Created += OnFileChanged;
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
}
I have a hidden share:
\\computername\Logs$
And I need to monitor file changes in that share.
I've decided to use FileSystemWatcher Class, but it doesn't raise any events. And it doesn't show any errors to me.
static void Main(string[] args)
{
FileWatcher fw = new FileWatcher(#"\\computername\Logs$", "*.*");
fw.Start();
}
class FileWatcher(string filePath, string mask)
{
FileSystemWatcher watcher;
watcher.Path = filePath;
watcher.Filter = mask;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Changed += Watcher_Changed;
watcher.Error += OnError;
public void Start()
{
watcher.InternalBufferSize = 64 * 1024;
watcher.EnableRaisingEvents = true;
Console.WriteLine("Watcher Started");
while (!Console.KeyAvailable)
{
Thread.Sleep(1000);
}
}
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine("File Changed");
}
private void OnError(object sender, ErrorEventArgs e)
{
Console.WriteLine("Error");
}
}
Does FileSystemWatcher work properly with hidden shares?
This code will not compile ,maybe you had errors while copy the code
and where the event handler Watcher_Changed, maybe you have mistake and put Watcher_Created instead
I've written this method which should check for file changes.
public static void watch()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = ConfigurationManager.AppSettings["OpticusFileLoc"];
watcher.Filter = "sigtrades.xml";
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
However, I get this error:
"No overload for 'OnChanged' matches delegate 'System.IO.SystemEventHandler'
Where am I going wrong?
Your OnChanged method needs to have the following signature:
void OnChanged(object sender, FileSystemEventArgs e);
Does it?
Is there some mechanism by which I can be notified (in C#) when a file is modified on the disc?
You can use the FileSystemWatcher class.
public void CreateFileWatcher(string path)
{
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = path;
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt";
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}
That would be System.IO.FileSystemWatcher.
Use the FileSystemWatcher. You can filter for modification events only.