簡體   English   中英

File.Copy()時Windows服務異常

[英]Windows Service Exception When File.Copy()

我駐留在OnStart()服務代碼引發Exception(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>

可能有多種原因。 請參閱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 
}

File.Copy額外參數true將覆蓋文件(如果已存在)。 我認為錯誤是文件已存在。

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

將代碼放在try..catch block並捕獲IOException異常。 您可以登錄文件以進行進一步調試。

當文件名,目錄名或卷標語法不正確時,我們將收到WinIOError錯誤(與調用堆棧有關)。 因此,只需檢查正確的路徑和文件名。

如果創建新線程,則需要確保處理該線程上引發的所有異常。 在Thread.Start()創建的線程上發生的任何未處理的異常都將導致您的應用程序終止。

具體來說,構造函數FileSystemWatcher(字符串路徑)File.Copy(字符串sourceFileName,字符串destFileName)會拋出一些您在當前代碼中未處理的異常。 這兩個都在單獨的線程上被調用。 由於文件已存在,很可能會得到IOException(對同一文件的多次更改將導致您的代碼嘗試多次復制該文件,從而導致第一次復制后的任何副本發生沖突)。

您可能應該更新File.Copy調用以使用File.Copy(字符串sourceFileName,字符串destFileName,布爾覆蓋)並將您的listener_Created函數包裝在一個有異常的try / catch塊中(而不是重新拋出它)。

我不知道為什么,但是在嘗試{} catch {}包圍了代碼之后,它的效果很好,有什么想法嗎? 這是代碼:

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();
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM