我有一个Windows服务(并通过创建类似的WinForms应用程序验证了代码),其中NotifyFilter不起作用。删除该行代码后,该服务将正常运行,并且可以在WinForms应用程序中看到事件处理程序启动。
我正在做的就是将文本文件拖放到FileSystemWatcher的输入目录中,以启动watcher_FileChanged
委托(delegate)。当我在其中放入_watcher.NotifyFilter = NotifyFilters.CreationTime;
时,它不起作用。当我将其拔出时,它可以正常工作。
谁能告诉我此过滤器是否做错了什么?
这是OnStart事件的FSW代码。
protected override void OnStart(string[] args)
{
_watcher = new FileSystemWatcher(@"C:\Projects\Data\Test1");
_watcher.Created += new FileSystemEventHandler(watcher_FileChanged);
_watcher.NotifyFilter = NotifyFilters.CreationTime;
_watcher.IncludeSubdirectories = false;
_watcher.EnableRaisingEvents = true;
_watcher.Error += new ErrorEventHandler(OnError);
}
private void watcher_FileChanged(object sender, FileSystemEventArgs e)
{
// Folder with new files - one or more files
string folder = @"C:\Projects\Data\Test1";
System.Console.WriteLine(@"C:\Projects\Data\Test1");
//Console.ReadKey(true);
// Folder to delete old files - one or more files
string output = @"C:\Temp\Test1\";
System.Console.WriteLine(@"C:\Temp\Test1\");
//Console.ReadKey(true);
// Create name to call new zip file by date
string outputFilename = Path.Combine(output, string.Format("Archive{0}.zip", DateTime.Now.ToString("MMddyyyy")));
System.Console.WriteLine(outputFilename);
//Console.ReadKey(true);
// Save new files into a zip file
using (ZipFile zip = new ZipFile())
{
// Add all files in directory
foreach (var file in Directory.GetFiles(folder))
{
zip.AddFile(file);
}
// Save to output filename
zip.Save(outputFilename);
}
DirectoryInfo source = new DirectoryInfo(output);
// Get info of each file into the output directory to see whether or not to delete
foreach (FileInfo fi in source.GetFiles())
{
if (fi.CreationTime < DateTime.Now.AddDays(-1))
fi.Delete();
}
}
最佳答案
我也一直在这种行为的麻烦。如果您逐步执行代码(并且查看MSDN documenation,则会发现NotifyFilter
开始时的默认值为:
NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite
因此,当您说
.NotifyFilter = NotifyFilters.CreationTime
时,您要清除掉其他值,这可以解释行为上的差异。我不确定NotifyFilters.CreationTime
为什么不捕获新文件...似乎应该,不应该!如果适合您,则可以仅使用
NotifyFilter
的默认值。如果要添加NotifyFilters.CreationTime
,建议您执行以下操作以添加新值,而不是替换现有值:_watcher.NotifyFilter = _watcher.NotifyFilter | NotifyFilters.CreationTime;
关于windows - FileSystemWatcher的NotifyFilter不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13708941/