服务中的文件系统观察程序不处理文件

时间:2018-04-30 07:23:14

标签: c# .net service filesystemwatcher

我需要从服务启动FileSystem Watcher。文件系统观察程序将文件添加到列表中,计时器已过去事件每1秒运行一些代码以处理来自观察者更新的列表中的输入文件

protected override void OnStart(string[] args)
{
    startwatching();
    System.Timers.Timer aTimer = new System.Timers.Timer();
    aTimer.Elapsed += ATimer_Elapsed;
    aTimer.Interval = 1000;
    aTimer.Enabled = true;
}

void startwatching()
{
    watcher = new FileSystemWatcher();
    watcher.Path = watchpath;
    // labelControl10.Text = "Monitoring-> " + watcher.Path;
    watcher.Filter = "*.*";
    // watcher.NotifyFilter = NotifyFilters.CreationTime;
    watcher.Created += new FileSystemEventHandler(copied);
    watcher.EnableRaisingEvents = true;
}

void copied(object sender, FileSystemEventArgs e)
{
    if (!robotprocesslist.Contains(e.FullPath))
    {
        try
        {
            robotprocesslist.Add(e.FullPath);
        }
        catch (OutOfMemoryException error)
        {
        }
    }
}

private void ATimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    //do stuff
}

但是没有处理任何文件。我做错了什么?请指教。

2 个答案:

答案 0 :(得分:0)

我的猜测是你的问题在这里:

if (!robotprocesslist.Contains(e.FullPath))

我怀疑你的列表是这样的:

file1.txt
file2.txt

它正在检查:

c:\file1.txt

所以永远不要在列表中找到该文件。

正如@Uwe Keim指出的那样 - 一些记录可能有助于证明这一理论。

答案 1 :(得分:0)

您应该使用队列而不是列表,并在专用线程中处理您的文件。目前还不清楚你在计时器事件中做了什么,但你很可能尝试多次处理相同的文件。

创建的事件只会在文件创建或文件复制开始时触发一次,并且可能需要几秒钟才能完成,因此您的文件很可能被锁定你的计时器事件。只要文件被复制,文件就会被锁定,因此在完成文件复制/创建之前,您将无法进行大量处理。

请在此处查看我的回答:Using file.move to rename new files in C# 它是一个控制台应用程序测试,它在不同的线程中实现文件处理(每个文件创建一个)。

相关问题