【发布时间】:2012-07-30 14:10:58
【问题描述】:
我每天多次收到来自不同用户的 xml 文件。这些通过 FTP 传送到我驱动器上的文件夹,例如 D:\batch。今天我使用计划任务检查这些文件,该任务启动 ASP.NET 页面并处理找到的文件并回答上传者并结束。此任务每 15 分钟运行一次,但上传者希望更快地得到答案,所以我正在尝试完成此任务。我创建了一个监视文件夹的 Windows 服务,并在创建文件时对其进行处理。
我遵循了几个不同的指南,但尤其是这个http://www.codeproject.com/Articles/32591/Creating-a-Windows-Service-for-Watching-System-Dir
第一个文件可以正常工作,但每次添加第二个文件时,它都会崩溃:
Exception Info: System.IO.IOException
Stack:
at System.IO.__Error.WinIOError(Int32, System.String)
at System.IO.File.InternalCopy(System.String, System.String, Boolean, Boolean)
at System.IO.File.Copy(System.String, System.String)
at FileMonitor.FilKigger.Watcher_Created(System.Object, System.IO.FileSystemEventArgs)
at System.IO.FileSystemWatcher.OnCreated(System.IO.FileSystemEventArgs)
at System.IO.FileSystemWatcher.NotifyFileSystemEventArgs(Int32, System.String)
at System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32, UInt32, System.Threading.NativeOverlapped*)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)
这是怎么回事?
一些代码:
protected override void OnStart(string[] args)
{
FileSystemWatcher Watcher = new FileSystemWatcher();
Watcher.Path = "D:\\FTP\\Batch\\";
Watcher.IncludeSubdirectories = true;
Watcher.Created += new FileSystemEventHandler(Watcher_Created);
Watcher.Deleted += new FileSystemEventHandler(Watcher_Deleted);
Watcher.EnableRaisingEvents = true;
}
这里只是将文件复制到新文件夹的代码。
void Watcher_Created(object sender, FileSystemEventArgs e)
{
File.Copy(e.FullPath, "D:\\newFolder\\" + e.Name);
Lg.WriteEntry("File moved", EventLogEntryType.Information);
}
捕获异常只会留下文件,但当然会保持服务运行。
【问题讨论】:
-
冷你提供异常消息,不仅仅是它的类型?如果有,请也发布 Inner Exception..
-
这个异常是在哪里抛出的(哪一行代码)?
-
请记住,创建文件时会触发 created 事件。因此,如果它是一个仍在传输的大文件,则该文件已创建(但未完成)并且您想要开始复制它,但该文件还没有真正存在。听起来有点模糊..希望你明白。也许这也是你的问题。
-
在 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 FileMonitor.FilKigger.Watcher_Created(Object sender, FileSystemEventArgs e
-
您发布的堆栈跟踪信息不足。异常的 HResult 值是多少?除此之外,这是完全常见的。您无法在创建文件后立即复制文件,创建它的应用程序仍然打开文件。你必须等待。
标签: c# file-io windows-services filesystemwatcher