Write a simple .NET wrapper service around FileSystemWatcher.Changed Event
I'm trying to configure a system where my Dropbox folder is constantly monitored and backed up incrementally by Windows backup whenever a change is made to any of the files in the folder (as a more reliable and free alternative to Dropbox's "packrat" addon). Ideally this can be done if I can invoke the incremental backup to be made whenever there's a file change event. Looks like Windows doesn't have an event trigger like that by default (at least from my googling around) and the only solution posted was to write a wrapper class around the FileSystemWatcher.Changed Event in .NET. Some programs do this but they're really expensive for such a simple function. I was wondering what they mean when they say "write a wrapper around this event"; I know basic programming in C and VB but its fairly rudimentary knowledge. Though I feel I can do it myself if I prod ar开发者_如何学运维ound long enough, pointers on how the process would go about would be very helpful.
What I'm exactly looking for is a program/service which will constantly keep monitoring a folder and whenever any file within that directory is changed or modified, calls an exe or bat file which we can program into whatever we want..
I don't know what exactly what write a wrapper class around FileSystemWatcher.Changed event
means - that's a bit too generic without any context.
But what you want to use in .NET is the FileSystemWatcher class. You'll need to listed to the Changed, Created, Deleted, and Rename events to get the notifications of each type.
There is an example program on the documentation for FileSystemWatcher that show's exactly how to setup an listen for events on the FileSystemWatcher. It displays all changes to the console, but you can change it to call a batch file instead with Process.Start().
static void Main(string[] args)
{
FileSystemWatcher fsw = new FileSystemWatcher(@"C:\foo");
fsw.Created += new FileSystemEventHandler(fsw_Created);
fsw.Changed += new FileSystemEventHandler(fsw_Changed);
fsw.EnableRaisingEvents = true;
Thread.Sleep(System.Threading.Timeout.Infinite);
}
static void fsw_Changed(object sender, FileSystemEventArgs e)
{
//Existing file has been modified
Console.WriteLine(e.Name + " has been modified.");
}
static void fsw_Created(object sender, FileSystemEventArgs e)
{
//A new file has been created
// put your code here to trigger the othe process
System.Console.WriteLine(e.Name + " has been created.");
}
But I must warn you: When the OnCreated event fires, it also fires the OnChangedEvent immediately and you may end up triggering your process more times than it needs to. You need to put some logic to prevent that.
精彩评论