Search code examples
c#windows-services

Best way to track Windows Service Unhandled Exception


I have a Windows Service application. The service is basically copying Excel files to a directory at specific hours, then reading Excel rows and finally updating SQL Server tables according to the data in the row it reads.

Recently, it crashes sometimes. While I was reviewing logs, I found it crashed because:

Application: WinCCServiceIzmit.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception.

Exception Info: System.IO.IOException

at System.IO.__Error.WinIOError(Int32, System.String)
at System.IO.FileStream.Init(System.String, System.IO.FileMode, System.IO.FileAccess, Int32, Boolean, System.IO.FileShare, Int32, System.IO.FileOptions, SECURITY_ATTRIBUTES, System.String, Boolean, Boolean, Boolean)
at System.IO.FileStream..ctor(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare, Int32, System.IO.FileOptions, System.String, Boolean, Boolean, Boolean)
at System.IO.StreamWriter.CreateFile(System.String, Boolean, Boolean)
at System.IO.StreamWriter..ctor(System.String, Boolean, System.Text.Encoding, Int32, Boolean)
at System.IO.StreamWriter..ctor(System.String, Boolean)
at System.IO.File.AppendText(System.String)
at WinccService.InnerOperation.WriteToFile(System.String)
at WinccService.InnerOperation.Stop()
at WinccService.WinccIzmit.start()
at System.Threading.ThreadHelper.ThreadStart_Context(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Threading.ThreadHelper.ThreadStart()

Do you guys have any idea how can I track where the problem comes from? Application has too many code rows.

Thanks.


Solution

  • Either subscribe to UnhandeledException Event or wrap on the highest level within your service (maybe within your method you start in OnStart) into a try-catch.

    By this way you can catch the exception and write more details into a separate log file to find out what happens.

    Nevertheless, inspecting your stack it seems the error occurs in WinccService.InnerOperation.WriteToFile() which will be called from WinccService.InnerOperation.Stop(). So looking into these two methods and who calls them should help you track down the issue. Additionally it seems that at this point a System.IO.StreamWriter.CreateFile() will be called and fails. Possible causes could be an invalid file name, the file already exists or a permission problem.