Question

I need to copy a file after it's been created and changed twice.

I have no idea how to do it, except by using 3 FileSystemWachers. First one on creation and two for changing.

Is there any easier way?

Was it helpful?

Solution

The FileSystemWatcher has several events that you can use to listen to different types of events on the file system. There is also a NotifyFilter property which you can use to specify which event types it should monitor.

So you don't need to use three different watchers; one would suffice. You just need some form of counter to keep track of how many changes were made to the file. Here's a quick example:

Dictionary<string, int> changeCounter = new Dictionary<string, int>();

...

FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\Path\To\Some\Folder";
watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite;
watcher.Created += OnCreated;
watcher.Changed += OnChanged;

...

private void OnCreated(object source, FileSystemEventArgs e)
{
    changeCounter.Add(e.FullPath, 0);
}
private void OnChanged(object source, FileSystemEventArgs e)
{
    if (changeCounter.ContainsKey(e.FullPath))
    {
        changeCounter[e.FullPath]++;
        if (changeCounter[e.FullPath] == 2) 
        {
            CopyFile(e.FullPath);
        }
    }
}

This would only call CopyFile after the watcher detected a file creation event and two file change events for a single file. You may also want to modify handle deletions, too, in case you are worried about files being created once, edited, deleted, recreated, and edited—this would trigger CopyFile even though, technically, the file has only been edited once after it was created.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top