How might I watch for a specific file to change in a directory using Mathematica/.NET code?
The following works in .NET but fires twice when you change the file.
using System;
public class Watcher
{
public static int exit=1;
static DateTime lastRead = DateTime.MinValue;
public static void Main()
{
System.IO.FileSystemWatcher watcher = new System.IO.FileSystemWatcher();
watcher.Path = "C:\\Users\\a\\Desktop";
watcher.NotifyFilter = System.IO.NotifyFilters.LastWrite;
watcher.Filter = "test.txt";
watcher.Changed += new System.IO.FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
while (exit != 0) ;
}
private static void OnChanged(object source, System.IO.FileSystemEventArgs e)
{
DateTime lastWriteTime = System.IO.File.GetLastWriteTime(e.FullPath);
if (lastWriteTime != lastRead)
{
Console.Write(
System.IO.File.ReadAllText(e.FullPath)
);
exit = 0;
lastRead = lastWriteTime;
}
}
}
to compile
C:\Windows\Microsoft.Net\Framework\v4.0.30319\csc.exe test.cs
Here is the starting code for Mathematica.
Needs["NETLink`"];
InstallNET[];
myHandler[source_, e_] := Print["File editted"];
w = NETNew["System.IO.FileSystemWatcher"];
LoadNETType["System.IO.NotifyFilters"];
w@Path = "C:\\Users\\a\\Desktop";
w@NotifyFilter = NotifyFilters`LastWrite;
w@Filter = "*.txt";
e = AddEventHandler[w@Changed, myHandler];
w@EnableRaisingEvents = True;