Skip to content

Instantly share code, notes, and snippets.

@ialex32x
Last active May 13, 2019 02:22
Show Gist options
  • Save ialex32x/6085726 to your computer and use it in GitHub Desktop.
Save ialex32x/6085726 to your computer and use it in GitHub Desktop.
c#. file system watcher.
/*
C# 监听文件变化
*/
var fsw = new FileSystemWatcher("../../scripts"); // 监视指定文件夹
fsw.Changed += fsw_Changed; // 注册事件回调
fsw.EnableRaisingEvents = true; // 启用事件通知 (事件异步触发)
/* ================================= */
void fsw_Changed(object sender, FileSystemEventArgs e)
{
Action f = () =>
{
try
{
var fi = new System.IO.FileInfo(e.FullPath);
if (lastWriteTime != fi.LastWriteTime) // 一次文件修改会触发多次Changed事件, 利用时间简单过滤一下同一次修改事件 {
using (var fs = fi.OpenRead())
{
using (var rd = new System.IO.StreamReader(fs))
{
var text = rd.ReadToEnd();
//Debug.WriteLine("fsw.Thread:" + System.Threading.Thread.CurrentThread.ManagedThreadId);
lastWriteTime = fi.LastWriteTime;
engine.Execute(text, scope);
rd.Close();
}
fs.Close();
}
}
}
catch (Exception err)
{
System.Diagnostics.Debug.WriteLine(err);
}
};
BeginInvoke(f); // 在界面线程中调用 (当前所在线程为回调线程, 不能直接调用f内容)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment