Avoiding IO Exception

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?
 
J

John Saunders

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.
 
M

Mike Hildner

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top