StreamReader: Avoiding IOException due to external lock

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am reading a text file using StreamReader. If while I have that stream
open I open the underlying text file in, say, Excel, Excel will announce that
the file is locked for reading and will offer to open it in Read-Only mode.

But if I do that, then my StreamReader immediately throws a
System.IO.IOException announcing, "The process cannot access the file because
another process has locked a portion of the file."

How can I access a file with a StreamReader in such a way that the file is
locked for reading AND it doesn't fail if another process also tries to
access the file in read-only mode?
 
Hi

This depends on how the file was opened by another process. If this file
has already been opened exclusively, it cannot be opened by StreamReader
anyway. This is defined by the operating system.

However, if this file is opened as read-only, you can use a try block to
test for the IOException and in the catch block open it as read-only with
the following code.

StreamReader sr = new StreamReader(new FileStream(@"c:\test1.xls",
FileMode.Open, FileAccess.Read, FileShare.Read));

Kevin Yu
Microsoft Online Community Support

============================================================================
==========================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
============================================================================
==========================

(This posting is provided "AS IS", with no warranties, and confers no
rights.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top