How do you open a file for reading like Notepad?

G

Guest

I was writing a program that was reading data from files (not making any
changes) and I used the File.OpenRead(filename) command. It threw an error
for one file because it said the file was being used by another process. But
I can open this file fine with Notepad and see the contents.

How can I open the file without trying to get a lock on it, since I just
want to read it? I would have imagine OpenRead would do that but it obviously
isn't.
 
N

Nicholas Paldino [.NET/C# MVP]

MrNobody,

What you want to do is use the FileStream constructor which takes a
FileAccess (with the Read value) and the FileShare value of ReadWrite (most
likely). Chances are something else is writing to the file and if you don't
specify that you can share it to write (and something is already trying to
write) then you are going to be denied access.

Hope this helps.
 
G

Guest

Nicholas,

that's exactly what I needed! Works great.

as a follow up question, assuming I used the previous method - would you
know what I could check to determine if a file is available for read to avoid
the exception from earlier ?
 
C

Chris Fulstow

Maybe try opening the file with:

FileInfo.Open(name, FileMode.Open, FileAccess.Read, FileShare.Read)
 
N

Nicholas Paldino [.NET/C# MVP]

MyNobody,

Well, you could try and open the file for reading (sharing as you wish)
and catch the exception. Of course, that's not always the best idea.

You could always call the CreateFile API function through the P/Invoke
layer, and interpret the return code (it will give you an error code if you
can't open the file).

Hope this helps.
 
C

Chris Dunaway

Chris said:
Maybe try opening the file with:

FileInfo.Open(name, FileMode.Open, FileAccess.Read, FileShare.Read)

That will fail if another process has opened the file for writing.
What FileShare.Read means is "Only allow other processes to Read the
file". If another process is already writing the file, you can very
well tell it *can't* write to the file!!
 

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

Top