0

My service code resided in OnStart() throws Exception(I) and service is stopped. I don't know why is there any ex. thrown?.. This is my code:

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

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>
Jon Senchyna
  • 7,867
  • 2
  • 26
  • 46
levi
  • 3,451
  • 6
  • 50
  • 86
  • You have 0 error handling. You are not ready to write windows services. The FileSystemWatcher's Created event almost always gets fired while the file is still in use. You need to master your code in a console application before venturing into services! – banging Jun 11 '12 at 13:49
  • I've rewritten the code from my working console app ;) – levi Jun 11 '12 at 13:54

4 Answers4

3

It could be any number of reasons. See File.Copy() documentation, especially the Exceptions section that document all the exceptions that could be thrown.

You need to wrap your File.Copy() and catch any exceptions so you can react appropriately:

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 
}
GazTheDestroyer
  • 20,722
  • 9
  • 70
  • 103
1

Extra parameter true in File.Copy will overwrite the file if already exists. I think the error is of file already exist.

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

Put the code in try..catch block and catch the IOException exception. You can do logging in file for further debugging.

We get the WinIOError error (as we get in call stack) when The filename , directory name, or volume label syntax is incorrect. So just check for the correct path and filename.

Romil Kumar Jain
  • 20,239
  • 9
  • 63
  • 92
0

If you create a new thread, you need to be sure to handle all exceptions thrown on that thread. Any unhandled exceptions that occur on a thread created by Thread.Start() will cause your application to terminate.

Specifically, the constructor FileSystemWatcher(string path) and File.Copy(string sourceFileName, string destFileName) throw several exceptions that you are not handling in your current code. Both of these are being called on a separate thread. It is most likely that you are getting an IOException, due to the file already existing (multiple changes to the same file will cause your code to try to copy it more than once, causing a collision on any copies after the first).

You should probably update your File.Copy call to use File.Copy(string sourceFileName, string destFileName, bool overwrite) and wrap your listener_Created function in a try/catch block that does soemthing with the exception (other than rethrowing it).

Jon Senchyna
  • 7,867
  • 2
  • 26
  • 46
  • Yes, it stopped for the exception, I saw that in the log, but Folders exists, even more, it work in Console app from where I've copied my service code – levi Jun 11 '12 at 13:59
0

I don't know why but after I surrounded my code by try {} catch {} it works excellent, Have any idea? This is code:

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();
        }
levi
  • 3,451
  • 6
  • 50
  • 86
  • 2
    Well what does bussite.txt contain? You're logging the exception so read it. – GazTheDestroyer Jun 11 '12 at 14:02
  • There is written file is used by another process. I got this but how do i get that file is not in use? that file is uploaded completely? – levi Jun 11 '12 at 14:20
  • This is because you are now catching the exceptions thrown by `listener_Created` in your separate thread. Any unhandled exceptions thrown in a thread created by Thread.Start() will cause your application to terminate, as stated in my answer. – Jon Senchyna Jun 11 '12 at 15:27