Hau*_*olt 16 c# filesystemwatcher visual-studio-2008
我做了一个小应用程序来响应文件夹中文件的更改.但是当我在Visual Studio 2008中编辑文件时,它从不会检测到任何内容.如果我在记事本中编辑文件,一切都按预期工作.
当然,Visual Studio会在某个时刻保存文件,但是当我关闭工作室时,观察者甚至不会触发.你知道我在这里缺少什么吗?
此示例代码(C#)应说明问题:
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher("C:\Test", "*.cs");
WaitForChangedResult changed = fileSystemWatcher.WaitForChanged(WatcherChangeTypes.All);
Console.Out.WriteLine(changed.Name);
Run Code Online (Sandbox Code Playgroud)
Tre*_*reb 27
这真是令人难以置信......当您尝试下面的示例程序并在VS中更改文件时,您会注意到输出窗口中有两行:
删除
改名
因此,Visual Studio永远不会更改现有文件,它会将内容保存到具有临时名称的新文件中,然后删除原始文件并将新文件重命名为旧名称.
实际上,这是一个很好的做法,因为如果你按照通常的方式(只是编写更改的文件,这将导致Changed事件被触发),可以在写入过程完成之前调用事件处理程序.如果事件处理程序处理文件内容,这可能会导致问题,因为它会处理不完整的文件.
换句话说:它不是一个bug,它是一个功能 ;-)
static class Program
{
[STAThread]
static void Main()
{
FileSystemWatcher FSW = new FileSystemWatcher("c:\\", "*.cs");
FswHandler Handler = new FswHandler();
FSW.Changed += Handler.OnEvent;
FSW.Created += Handler.OnEvent;
FSW.Deleted += Handler.OnEvent;
FSW.Renamed += Handler.OnEvent;
FSW.EnableRaisingEvents = true;
System.Threading.Thread.Sleep(555000);
// change the file manually to see which events are fired
FSW.EnableRaisingEvents = false;
}
}
public class FswHandler
{
public void OnEvent(Object source, FileSystemEventArgs Args)
{
Console.Out.WriteLine(Args.ChangeType.ToString());
}
}
}
Run Code Online (Sandbox Code Playgroud)
通过指定 NotifyFilter 属性解决:
FileSystemWatcher w = new FileSystemWatcher();
w.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.CreationTime;
Run Code Online (Sandbox Code Playgroud)