基本上,我要做的是监视放入具有特定文件扩展名 (*.req) 的文件夹中的新文件,因此我开始使用 System.IO.FileSystemWatcher 功能进行设置。因此,在我启动程序后,我只需将一组 *.req 文件复制到我的监视文件夹中,它们似乎第一次运行良好,没有任何错误。这些文件随后被重命名、处理,然后被删除。我随后会重新复制相同的 *.req 文件,现在这一次它吹出一个 IOException is unhandled 错误,详细如下:
System.IO.IOException was unhandled
HResult=-2147024864
Message=The process cannot access the file 'C:\accucom\reqdir\hcd - Copy (2).req' because it is being used by another process.
Source=mscorlib
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)
at System.IO.File.Copy(String sourceFileName, String destFileName)
at CollectV2.CollectV2.OnChanged(Object source, FileSystemEventArgs e) in C:\accucom\CollectV2\CollectV2.cs:line 375
at System.IO.FileSystemWatcher.OnCreated(FileSystemEventArgs e)
at System.IO.FileSystemWatcher.NotifyFileSystemEventArgs(Int32 action, String name)
at System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* overlappedPointer)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
InnerException:
这是我正在使用的代码片段,因为我想知道这里可能缺少什么:
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = GlobalVars.REQpath;
// Only watch *.req files.
watcher.Filter = "*.req";
watcher.Created += new FileSystemEventHandler(OnChanged);
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
string rqfile = e.FullPath.Replace(".req", ".re0");
//System.IO.File.Delete(rqfile);
System.IO.File.Copy(e.FullPath, rqfile);
System.IO.File.Delete(e.FullPath);
ThreadPool.QueueUserWorkItem(wcbdoRequestFile, rqfile);
}