StreamReader locks the file

  • Thread starter Thread starter fniles
  • Start date Start date
F

fniles

I am using VB.NET 2008 and StreamReader to read from a file on our server.
While the file is open in this VB.NET program, another program written in
VB6 at the same time trying to append to the same file, and it got
"Permission Denied" error.
I am wondering if I can use StreamReader without locking the file for update
by other program.

This is how I open the file
srBCAS = New StreamReader(m_sServer & "\log.txt",
System.Text.Encoding.Default)

Thank you
 
fniles said:
I am using VB.NET 2008 and StreamReader to read from a file on our server.
While the file is open in this VB.NET program, another program written in
VB6 at the same time trying to append to the same file, and it got
"Permission Denied" error.
I am wondering if I can use StreamReader without locking the file for
update by other program.

You have to allow shared access explicitly:

\\\
Dim Stream As New FileStream( _
"C:\foo.txt", _
FileMode.Open, _
FileAccess.Read, _
FileShare.ReadWrite _
)
Using Reader As New StreamReader(Stream)
...
End Using
///
 
I am using VB.NET 2008 and StreamReader to read from a file on our server.
While the file is open in this VB.NET program, another program written in
VB6 at the same time trying to append to the same file, and it got
"Permission Denied" error.
I am wondering if I can use StreamReader without locking the file for update
by other program.

This is how I open the file
srBCAS = New StreamReader(m_sServer & "\log.txt",
System.Text.Encoding.Default)

Thank you

I beleive you'd better use "Using" statement to do all the disposal
operation automatically, thus the underlying and all resources will be
freed.

Using srBCAS As New StreamReader(m_sServer & "\log.txt",
System.Text.Encoding.Default)

' Code...Typically srBACS.ReadToEnd()

End Using

Hope this helps,

Onur Güzel
 
kimiraikkonen said:
I beleive you'd better use "Using" statement to do all the disposal
operation automatically, thus the underlying and all resources will be
freed.

Using srBCAS As New StreamReader(m_sServer & "\log.txt",
System.Text.Encoding.Default)

' Code...Typically srBACS.ReadToEnd()

End Using

Hope this helps,

Onur Güzel

That is helpful for making sure that the file is properly closed when
you are done with it.

However, that is not the main problem here. The OP want's one process to
be able to write to the file while another process is still reading it.

As already mentioned, the solution is to specify the sharing mode when
opening the stream.
 
Thank you. That fixed my problem.
Thanks again

Herfried K. Wagner said:
You have to allow shared access explicitly:

\\\
Dim Stream As New FileStream( _
"C:\foo.txt", _
FileMode.Open, _
FileAccess.Read, _
FileShare.ReadWrite _
)
Using Reader As New StreamReader(Stream)
...
End Using
///
 
Back
Top