ReadWrite to file, file access errors

nathani

New member
Joined
Aug 20, 2009
Messages
4
Programming Experience
1-3
I'm having some problems with file access to a log file that my program is writing to. I have it all set up fine and it logs the data being pulled off the network to a file. But when I copy and paste that log file with windows explorer (XP) or I open the file with a log viewer program that I've made there are access errors. I've caught the errors in a try catch loop

VB.NET:
   Public Sub write_data_to_file(ByVal filePath As String, ByVal tempString As String)
      Static Dim alreadyDisplayed As Boolean = False
      Dim yesNo As DialogResult

      Try
         logWrite = New StreamWriter(filePath, True)
         logWrite.WriteLine(tempString)
         logWrite.Close()
      Catch ex As IOException
         If (Not alreadyDisplayed) Then
            alreadyDisplayed = True
            yesNo = MessageBox.Show(ex.Message, "Access Denied", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            alreadyDisplayed = False
         End If
      End Try
   End Sub

I'm not sure what explorers problem is, but I can open the file with notepad or wordpad and no file exceptions are thrown. But the log reader program will make the logging program throw exceptions. How do I a) make my logging program safe so that explorer will not cause it to throw exceptions (or do I just catch the exceptions and live with it) and b) make the log reading program open the file in such a way that it doesn't make the log program throw errors.

The log reader opens the file like this:

VB.NET:
Dim objReader As New System.IO.StreamReader(logFilePath)

Thanks in advance for any help,
Nathan
 
Open it with a different file share/file lock parameters. Investigate the other overloads of New System.IO.StreamReader(logFilePath, ..., ...)
 
Both StreamWriter and StreamReader opens the FileStream with FileShare.Read flag, so if writer opens first then the reader is allowed to read, but if reader opens it first then writer will not be allowed. If any of these have the file open then you can't move the file in Explorer, but you can copy it.
FileShare Enumeration (System.IO)
 
That sounds like the issue to me. The StreamWriter opens the stream and writes to file and closes. Whereas the log reader has the StreamReader open for as long as it takes to import the data and then closes it. So imagine the StreamWriter tries to open while the StreamReader is already open and fails.

So what is my solution? Should I leave the StreamWriter open for the duration of the program, or is there a way to let the writer open with the reader or a like device already accessing the file for read purposes only. Like I said, I can open the file no problems with notepad and other readers so I'm thinking there must be a way to accomplish this.
 
Back
Top