[英]How to update fileSystemWatch in order to find newly created file in C#?
I have a console app which is checking a logfile for newly updated data, if yes, then copies them in a db. 我有一个控制台应用程序,它正在检查日志文件中是否有新更新的数据,如果是,则将它们复制到数据库中。
Currently I'm using FileSystemWatcher to track any changes in the log. 目前,我正在使用FileSystemWatcher来跟踪日志中的所有更改。
What I would like to do is, to track if a new
logfile is created, if yes, then to invoke myMethod() in the new logfile. 我想做的是,跟踪是否创建了new
日志文件(如果是),然后在新的日志文件中调用myMethod()。 Since I'm new in C# I have a question, should a create a second fileSystemWatcher, or there's a way to update the current one in order to include also this case? 因为我是C#的新手,所以我有一个问题,应该创建第二个fileSystemWatcher,还是有一种方法可以更新当前文件,以便也包括这种情况? I already checked stackoverflow and although I found many posts on fileSystemWatcher, I'm not really sure on how to proceed. 我已经检查了stackoverflow,尽管我在fileSystemWatcher上找到了很多帖子,但是我不确定如何继续。 Here's my code: 这是我的代码:
foreach (string path in paths)
{
if (path.Length > 0)
{
logFile.read(path, errorListAndLevel);
FileSystemWatcher logWatcher = new FileSystemWatcher();
logWatcher.Path = Path.GetDirectoryName(path);
logWatcher.Filter = Path.GetFileName(path);
logWatcher.IncludeSubdirectories = false;
logWatcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size;
logWatcher.Changed += new FileSystemEventHandler(delegate (object sender, FileSystemEventArgs e)
{
logFile.myMethod(errorListAndLevel, e.FullPath.ToString());
});
logWatcher.EnableRaisingEvents = true;
}
}
I thought of creating a logWatcher.Created... but it isn't working. 我想创建一个logWatcher.Created ...,但是不起作用。
logWatcher.Created += new FileSystemEventHandler(delegate (object sender, FileSystemEventArgs e)
{
logFile.myMethod(errorListAndLevel, e.FullPath.ToString());
});
The problem is the following line 问题是以下行
logWatcher.Filter = Path.GetFileName(path);
It filters all files and makes the fileWatcher
only whatch that one file. 它过滤所有文件,并使fileWatcher
仅处理该文件。 Now this makes the fileWatcher
not calling the event Created
unless a second a file with the exact same name will be created. 现在,这将使fileWatcher
不会调用事件Created
除非将创建具有完全相同名称的文件。
When you comment that line it should work fine. 当您注释该行时,它应该可以正常工作。
Additionaly you could do this instead: 另外,您可以这样做:
logWatcher.Filter = "*.log";
This will filter all files with the ending .log
which is what you want from what I can see. 这将过滤所有以.log
结尾的文件,这就是我所看到的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.