Read a file that is being used by another process.

  • Thread starter Thread starter funkmusha
  • Start date Start date
F

funkmusha

I am trying to read a log file using vb.net. I get an error stating
"The process cannot access the file 'C:\test.log' because it is being
used by another process." Below is a sample of what I am trying to do.
The var logFileName is being passed into the function.

Dim line as String
Dim sr As New StreamReader(logFileName) 'It dies on this line

Do
line = sr.ReadLine()
Loop Until line is Nothing

sr.Close()

I am new to dot net and not sure if there is another class I should be
using other than the StreamReader class. I just want to read the file
line by line nothing more. Any help would be great. Thanks
 
If the other process has opened the file with exclusive rights, meaning
it is locked to all other processes, then you can't read it. If the
other process opens it as a shared file, then you should be able to also
open and read the file. If you have control over the other process,
then change the way it is opening the file.

Tom
 
funkmusha said:
I am trying to read a log file using vb.net. I get an error stating
"The process cannot access the file 'C:\test.log' because it is being
used by another process." Below is a sample of what I am trying to do.
The var logFileName is being passed into the function.

Dim line as String
Dim sr As New StreamReader(logFileName) 'It dies on this line

Try to open the file with 'FileShare.ReadWrite', which means that other
processes are still allowed to read/write the file:

\\\
Dim fs As New FileStream( _
"C:\test.txt", _
FileMode.Open, _
FileAccess.Write, _
FileShare.ReadWrite _
)
Dim sr As New StreamReader(fs)
....
sr.Close()
///
 
Herfried said:
Try to open the file with 'FileShare.ReadWrite', which means that other
processes are still allowed to read/write the file:

\\\
Dim fs As New FileStream( _
"C:\test.txt", _
FileMode.Open, _
FileAccess.Write, _
FileShare.ReadWrite _
)
Dim sr As New StreamReader(fs)
...
sr.Close()

If he is only going to read the file, then perhaps FileAccess.Read
would be a better choice than FileAccess.Write.
 
Chris,

Chris Dunaway said:
If he is only going to read the file, then perhaps FileAccess.Read
would be a better choice than FileAccess.Write.

Thank you for making me aware of that. I wrote the sample for
'StreamWriter' and then found out that the OP used a 'StreamReader'. I
simply forgot to change the 'FileAccess' to 'Read'.
 
Back
Top