我有一个 Windows 服务,它监视文件夹中的新文件并运行一个进程。但是,每次我将文件放入受监控的文件夹时,该服务都会崩溃。这是我收到的异常:
应用程序:框架版本:v4.0.30319 描述:进程因未处理的异常而终止。异常信息:System.IO.IOException 堆栈:在 System.IO._Error.WinIOError (Int32, System.String) 在 System.IO。_Error.WinIOError() 在 System.IO.File.Move(System.String, System.String) 在 Service.Service.Process(System.String, System.String) 在 Service.Service.OnChanged(System.Object, System. IO.FileSystemEventArgs) 在 System.IO.FileSystemWatcher.OnCreated(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*)
一切正常,然后突然之间,每次我使用它时它都会崩溃。我不记得改变任何会导致这种情况的东西。这是我的代码:
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()
{
}