Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

StreamReader - "...cannot access the file"

Status
Not open for further replies.

NCYankee1

Programmer
Mar 27, 2001
66
0
0
US
I've searched the archives here and tried things I've found but nothing is working. Here's my problem: My Windows Service has to read the contents (1 line) of txt files. A source file comes in, I read it and process. Then I read the next source file. Sporadically I get the following exception: "The process cannot access the file "D:\Source\inputfile.txt" because it is being used by another process." Here is the function where I am sporadically getting this message:

Code:
Private Function GetTranIdFromFile(ByVal astrFullPath As String) As String
' astrFullPath is D:\Source\inputfile.txt (different file name each time)
        Dim strTranId As String
        Dim objStreamReader As StreamReader
        Try
             objStreamReader = New StreamReader(astrFullPath)
            strTranId = objStreamReader.ReadLine().Trim()
            objStreamReader.Close()
            objStreamReader = Nothing  
        Catch ex As Exception
            'sometimes I get the "being used by another user" error
        End Try
        Return strTranId
    End Function

The first file seems to process ok. The second one seems to fail sometimes and is ok other times, etc. Can anyone tell me why I am getting that exception?

Thanks!
-Mike
 
Try moving your .close call into the finally block of your try..catch. You want to make sure it closes, as that's what calls .Dispose on the underlying file handle.

Chip H.


____________________________________________________________________
Donate to Katrina relief:
If you want to get the best response to a question, please read FAQ222-2244 first
 
Perhaps that there is a kind of StreamWriter which creates the "D:\Source\inputfile.txt". Make sure that it has been closed before the objStreamReader begin to read it.
 
If you do not have control over the process that places the file in your source directory, then you can do nothing other than catch the error and try again. Traditionally programming against the file system requires a great deal of exception/retry processing. In .Net much of this is hidden from you by the framework. This is one case where the framework is not able to shelter you from this problem. The problem is occurring because another process still has a hold on the file. Perhaps there is a StreamWriter or perhaps the file is still being copied to the location.

stravis
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top