Windows服务异常时File.Copy()

本文关键字:Copy File 服务 异常 Windows | 更新日期: 2023-09-27 18:36:44

我的服务代码驻留在OnStart()抛出异常(I)并且服务已停止。我不知道为什么会有前任被抛出?..这是我的代码:

public Service1()
{
    InitializeComponent();
}
Thread thread;
protected override void OnStart(string[] args)
{
    thread = new Thread(delegate()
    {
        string path = @"D:'levani'FolderListenerTest'ListenedFolder";
        FileSystemWatcher listener;
        listener = new FileSystemWatcher(path);
        listener.Created += new FileSystemEventHandler(listener_Created);
        listener.EnableRaisingEvents = true;
    });
    thread.Start();
}
public void listener_Created(object sender, FileSystemEventArgs e)
{
    File.Copy(e.FullPath, @"D:'levani'FolderListenerTest'CopiedFilesFolder'F" + e.Name);
}
protected override void OnStop()
{
    thread.Abort();
}

日志

Log Name:      Application
Source:        .NET Runtime
Date:          6/11/2012 5:33:27 PM
Event ID:      1026
Task Category: None
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      Levan-PC
Description:
Application: FolderListenerService.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.IOException
Stack:
   at System.IO.__Error.WinIOError(Int32, System.String)
   at System.IO.File.InternalCopy(System.String, System.String, Boolean)
   at System.IO.File.Copy(System.String, System.String)
   at FolderListenerService.Service1.listener_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*)
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name=".NET Runtime" />
    <EventID Qualifiers="0">1026</EventID>
    <Level>2</Level>
    <Task>0</Task>
    <Keywords>0x80000000000000</Keywords>
    <TimeCreated SystemTime="2012-06-11T14:33:27.000000000Z" />
    <EventRecordID>18314</EventRecordID>
    <Channel>Application</Channel>
    <Computer>Levan-PC</Computer>
    <Security />
  </System>
  <EventData>
    <Data>Application: FolderListenerService.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.IOException
Stack:
   at System.IO.__Error.WinIOError(Int32, System.String)
   at System.IO.File.InternalCopy(System.String, System.String, Boolean)
   at System.IO.File.Copy(System.String, System.String)
   at FolderListenerService.Service1.listener_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*)
</Data>
  </EventData>
</Event>

Windows服务异常时File.Copy()

这可能是许多原因。请参阅 File.Copy() 文档,尤其是记录所有可能引发的异常的异常部分。

您需要包装 File.Copy() 并捕获任何异常,以便做出适当的反应:

public void listener_Created(object sender, FileSystemEventArgs e)
{
    try
    {
        File.Copy(e.FullPath, @"D:'levani'FolderListenerTest'CopiedFilesFolder'F" + e.Name);
    }
    catch {FileNotFoundException e)
    { 
        //do something if file isn't there
    }
    catch {UnauthorizedAccessException e)
    { 
        //do something if invalid permissions
    }
    //etc 
}

中的额外参数 true File.Copy将覆盖该文件(如果已存在)。我认为错误是文件已经存在。

File.Copy(e.FullPath, @"D:'levani'FolderListenerTest'CopiedFilesFolder'F" + e.Name,true);

将代码放入try..catch block并捕获IOException异常。您可以在文件中进行日志记录以进行进一步调试。

当文件名、目录名或卷标语法不正确时,我们会收到WinIOError错误(当我们在调用堆栈中时)。因此,只需检查正确的路径和文件名即可。

我不知道

为什么,但是在我通过尝试{}捕获{}包围了我的代码之后,它工作得很好,知道吗?这是代码:

public Service1()
        {
            InitializeComponent();
        }
        Thread thread;
        protected override void OnStart(string[] args)
        {
            try
            {
                thread = new Thread(delegate()
                {
                    string path = @"D:'levani'FolderListenerTest'ListenedFolder";
                    FileSystemWatcher listener; listener = new FileSystemWatcher(path);
                    listener.Created += new FileSystemEventHandler(listener_Created);
                    listener.EnableRaisingEvents = true;
                });
                thread.Start();
            }
            catch (Exception ex)
            {
                File.WriteAllText(@"D:'levani'bussite.txt", "thread: " + ex.ToString());
            }
        }
        public void listener_Created(object sender, FileSystemEventArgs e)
        {
            try
            {
                File.Copy(e.FullPath, @"D:'levani'FolderListenerTest'CopiedFilesFolder'F" + e.Name);
            }
            catch (Exception ex)
            {
                File.WriteAllText(@"D:'levani'bussite.txt", "File copy ex: " + ex.ToString());
            }
        }
        protected override void OnStop()
        {
            thread.Abort();
        }

如果创建新线程,则需要确保处理该线程上引发的所有异常。 在 Thread.Start() 创建的线程上发生的任何未经处理的异常都将导致应用程序终止。

具体来说,构造函数 FileSystemWatcher(字符串路径)和 File.Copy(字符串源文件名,字符串 dest文件名)会引发几个您在当前代码中未处理的异常。 这两者都是在单独的线程上调用的。 由于文件已经存在,您很可能正在获得 IOException(对同一文件的多次更改将导致您的代码尝试多次复制它,从而导致第一个副本之后的任何副本发生冲突)。

您可能应该更新 File.Copy 调用以使用 File.Copy(字符串源文件名、字符串 destFileName、bool overwrite),并将listener_Created函数包装在 try/catch 块中,该块执行异常操作(除了重新抛出它)。