Beginner programmer here....hope it makes sense :)
I have created a console app that I need to run in the background and watch a directory for any changes/rename events. I have used the FileWatcher class and have added the event handlers as so:
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
and defined the handlers then below like so:
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);
I would like to be able to add in some code that dumps any files that have changed/renamed into another local directory but I dont know where to start. At the minute the console is writing back the Fullpath to me but ideally I would like it to copy that into another folder
Thanks Guys
You can use string destination = Path.Combine(localDirectory, e.Name);
to create the destination path and File.Copy(e.FullPath, destination);
actually copies the file.
Note that a process may still be writing to the file when you get the Changed
event, so you may get an exception or copy half-processed data. Also you should think about what to do if the file already exists in your local directory (notice the File.Copy(string, string, bool overwrite)
overload).
Also make sure you check if the changed item is a file and not a directory (for instance, by using File.Exists(e.FullPath)
.