Cra*_*aig 36 .net c# windows-8
我有一些代码使用FileSystemWatcher来监视我的应用程序之外的文件更改.
在Windows 7上,使用.NET 4,下面的代码将检测文件何时编辑并保存在记事本等应用程序中,同时我的应用程序正在运行.但是,这种逻辑在Windows 8上使用.NET 4无效.具体来说,FileSystemWatcher的Changed事件永远不会触发.
public static void Main(string[] args)
{
const string FilePath = @"C:\users\craig\desktop\notes.txt";
if (File.Exists(FilePath))
{
Console.WriteLine("Test file exists.");
}
var fsw = new FileSystemWatcher();
fsw.NotifyFilter = NotifyFilters.Attributes;
fsw.Path = Path.GetDirectoryName(FilePath);
fsw.Filter = Path.GetFileName(FilePath);
fsw.Changed += OnFileChanged;
fsw.EnableRaisingEvents = true;
// Block exiting.
Console.ReadLine();
}
private static void OnFileChanged(object sender, FileSystemEventArgs e)
{
if (File.Exists(e.FullPath))
{
Console.WriteLine("File change reported!");
}
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以改变NotifyFilter以包含NotifyFilters.LastWrite,它可以解决我的问题.但是,我想了解为什么此代码在Windows 7上有效但现在无法在Windows 8上触发Changed事件.我也很想知道在Windows 8中运行时是否有办法恢复我的Windows 7 FileSystemWatcher行为(不更改NotifyFilter).
FileSystemWatcher 是出了名的不可靠。尝试订阅所有事件,看看其他事件是否会发生。您可以尝试的一件事是使用计时器定期检查文件是否发生更改,例如每两秒一次,而不是使用 FileSystemWatcher。
| 归档时间: |
|
| 查看次数: |
4180 次 |
| 最近记录: |