我有一个Windows服务,它监视文件夹中的新文件并运行一个进程 . 但是,每次将文件放入受监视文件夹时,服务都会崩溃 . 这是我收到的例外情况:
应用程序:框架版本:v4.0.30319描述:由于未处理的异常,进程终止 . 异常信息:System.IO.IOException Stack:位于System.IO.File.Move的System.IO._Error.WinIOError()处的System.IO._Error.WinIOError(Int32,System.String)处(System.String,System . 字符串)位于System.IO.FileSystemWatcher.OnCreated(System.IO.FileSystemEventArgs)Service.Service.OnChanged(System.Object,System.IO.FileSystemEventArgs)的Service.Service.Process(System.String,System.String)处 . System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32,UInt32,System.Threading)上System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32,UInt32,System.Threading.NativeOverlapped *)的System.IO.FileSystemWatcher.NotifyFileSystemEventArgs(Int32,System.String) .NativeOverlapped *)
一切都很好,然后突然间,每次使用它都会崩溃 . 我不记得改变会导致这种情况的任何事情 . 这是我的代码:
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()
{
}
4 回答
我怀疑在某些情况下进程仍然锁定了文件 . 只是想知道,你为什么不打电话:
在WaitForExit()之后 .
为什么在确定进程存在为0之后才进行以下检查,如下所示,
我怀疑在您尝试移动时扫描进程是否仍在隔离文件 .
参考:know how to check a file is locked?
当然,你应该适当地处理其他条件......
我在创建进程之前添加了Thread.Sleep(5000) . 这种方法效果很好,但它在5秒内扫描每个文件 . 而且,正如人们所说的人一样,感觉有点像黑客 .
可能是另一个进程,比如你手动启动的扫描程序的另一个实例,在你尝试移动它的那一刻仍然保持对文件的锁定?
您应该使用Process Monitor来查看哪些进程正在访问该文件 .
无论如何,你不扫描新文件,你总是扫描整个文件夹L:\ Test . 这是你的意图吗?