Avoiding IO Exception

  • Thread starter Thread starter Mike Hildner
  • Start date Start date
M

Mike Hildner

I'm writing a service application (VB.NET) that, for debugging, writes to a
log file.

Sometimes, but not always, when I start the service, it stops because of an
unhandled exception. The event log shows:
Service cannot be started. System.IO.IOException: The process cannot access
the file <my file name> because it is being used by another process.

I *thought* I took care of this by making the logging methods shared, but I
guess it doesn't work:

Public Class Logger

Public Shared Sub LogText(ByVal message As String)

Dim fs As FileStream = New FileStream(Application.StartupPath & "\Sleuth
NCIC Server.log", FileMode.Append)

AddText(fs, message)

fs.Close()

End Sub

Private Shared Sub AddText(ByVal fs As FileStream, ByVal value As String)

Dim info As Byte() = New UTF8Encoding(True).GetBytes(Now & " - " & value &
vbCrLf)

fs.Write(info, 0, info.Length)

End Sub

End Class

Any ideas on what I can do?
 
Mike Hildner said:
I'm writing a service application (VB.NET) that, for debugging, writes to a
log file.

Sometimes, but not always, when I start the service, it stops because of an
unhandled exception. The event log shows:
Service cannot be started. System.IO.IOException: The process cannot access
the file <my file name> because it is being used by another process.

I *thought* I took care of this by making the logging methods shared, but I
guess it doesn't work:

Public Class Logger

Public Shared Sub LogText(ByVal message As String)

Dim fs As FileStream = New FileStream(Application.StartupPath & "\Sleuth
NCIC Server.log", FileMode.Append)

AddText(fs, message)

fs.Close()

End Sub

Private Shared Sub AddText(ByVal fs As FileStream, ByVal value As String)

Dim info As Byte() = New UTF8Encoding(True).GetBytes(Now & " - " & value &
vbCrLf)

fs.Write(info, 0, info.Length)

End Sub

End Class

Any ideas on what I can do?

"Shared" has nothing to do with allowing simultaneous access to the file!
Look at the FileStream constructors for one which allows you to specify
sharing.
 
Wow, that was quick, thanks. Guess I'm confusing shared with attempting to
only allow one thread of execution. I don't think I want to be writing two
messages at the same time, maybe make the method thread safe?
 
Back
Top