首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FIleSystemWatcher IOException

FIleSystemWatcher IOException
EN

Stack Overflow用户
提问于 2011-08-31 17:12:26
回答 5查看 3.9K关注 0票数 3

我有一个Windows服务,它监视文件夹中的新文件并运行进程。但是,每当我将文件放入受监视的文件夹时,该服务就会崩溃。以下是我收到的例外情况:

应用程序:框架版本: v4.0.30319描述:进程由于一个未处理的异常而终止。例外信息: System.IO.IOException Stack: at System.IO._Error.WinIOError(Int32,System.String) at System.IO._Error.WinIOError() at System.IO.File.Move(System.String,System.String) at Service.Service.Process(System.String,System.String) at Service.Service.OnChanged(System.Object,System.IO.FileSystemEventArgs) 在System.IO.FileSystemWatcher.NotifyFileSystemEventArgs(Int32,System.String)在System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32,UInt32,System.Threading.NativeOverlapped*)在System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32,UInt32,System.Threading.NativeOverlapped*)

一切正常,然后突然间,每次我使用它的时候,它都会崩溃。我不记得有什么改变会导致这一切的。这是我的代码:

代码语言:javascript
复制
public Service()
{
    InitializeComponent();
}

protected override void OnStart(string[] args)
{
    FileSystemWatcher watcher = new FileSystemWatcher(ConfigurationManager.AppSettings["UploadPath"]);

    watcher.Created += new FileSystemEventHandler(OnChanged);
    watcher.EnableRaisingEvents = true;
}

public static void OnChanged(object source, FileSystemEventArgs e)
{
    Process(e.Name, e.FullPath);
}

public static void Process(string fileName, string path)
{
    string newPath = Path.Combine(ConfigurationManager.AppSettings["NewPath"], fileName);

    Process process = new Process();

    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.FileName = @"C:\Program Files\Microsoft Security Client\Antimalware\mpcmdrun";
    process.StartInfo.Arguments = " -scan -scantype 3 -file L:\\Test\\";

    process.Start();

    string output = process.StandardOutput.ReadToEnd();
    process.WaitForExit();

    if (process.ExitCode == 0)
    {
        File.Move(path, cleanPath);
    }

    else
    {
        TextWriter tw = new StreamWriter(ConfigurationManager.AppSettings["FailedPath"] + fileName + ".txt");
        tw.WriteLine(output);
        tw.Close();

        File.Delete(path);
    }
}
protected override void OnStop()
{

}
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-09-02 13:38:29

我在创建流程之前添加了Thread.Sleep(5000)。这很好,但它可以在5秒内扫描每个文件。而且,就像人们所说的,这感觉有点无趣。

票数 0
EN

Stack Overflow用户

发布于 2011-08-31 17:34:58

在某些情况下,我怀疑该进程仍然对文件有锁。只是想知道,你为什么不打电话:

代码语言:javascript
复制
process.Close(); // Frees all the resources that are associated with this component

在WaitForExit()之后。

票数 1
EN

Stack Overflow用户

发布于 2011-09-02 13:44:49

你手动启动的另一个扫描程序的另一个实例,在你试图移动它的时候,是否仍然持有文件的锁?

您应该使用过程监视器查看哪些进程正在访问该文件。

无论如何,你不扫描新文件,你总是扫描整个文件夹L:\Test。这就是你的意图吗?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7260792

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档