StreamReader question

kazmax

Member
Joined
Sep 24, 2005
Messages
8
Programming Experience
10+
I am using the StreamReader class very successfully to open and process a text file. However there is one small problem which I need to design for.

The text file arrives at a known location from an external process over which I have no control. Because of the way this is implemented most of the time this isn't going to cause me any problem.

However, there is the chance that my application might try to open the file whilst it is still being written by another external process.

How do I go about ensuring I have sole access to a text file? I don't mind having a delay-and-retry loop, but I'm struggling to understand how I can code the decision logic.

The StreamReader class is instantiated as follows:

Dim oTxt As New System.IO.StreamReader(FilNam)

I'm not sure how to go about coding the retry loop.

 
Last edited:
you could put that line in a Try/Catch block because the streamreader will give you an exception if the file is in use:

VB.NET:
Dim intNumRetries
Do While intNumRetries <= 5
  Try
    Dim oTxt As New System.IO.StreamReader(FilNam)
  Catch
    intNumRetries += 1
  End Try
Loop

if there's an error it'll be caught and then it'll retry again, now in this example it'll immediatly retry but you're going to want to use a timer control with this so it'll pause for a few seconds before retrying

i hope this helps, if you need a more specific example feel free to ask
 
Back
Top