Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open file ReadOnly

Tags:

c#

file-io

Currently, this is how I'm opening a file to read it:

 using (TextReader reader = new StreamReader(Path.Combine(client._WorkLogFileLoc, "dump.txt"))) {     //do stuff } 

How can I open the file in ReadOnly mode, so that if another process has the file open at the same time, my program can still read it.

like image 781
xbonez Avatar asked Feb 11 '11 01:02

xbonez


People also ask

Can you open a file in read only?

Navigate to the folder containing the file you want to open as read-only. Instead of clicking the main part of the “Open” button, click the down arrow on the right side of the “Open” button. Select “Read-Only” from the drop-down menu.

What does open read only mean?

Read-only is a file attribute which only allows a user to view a file, restricting any writing to the file. Setting a file to “read-only” will still allow that file to be opened and read; however, changes such as deletions, overwrites, edits or name changes cannot be made.


2 Answers

The typical problem is that the other process has the file open for writing. All of the standard File methods and StreamReader constructors open the file with FileShare.Read. That cannot work, that denies write sharing. You cannot deny writing, the other process was first and got write access. So you'll be denied access instead.

You have to use FileShare.ReadWrite, like this:

var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);  using (var sr = new StreamReader(fs)) {     // etc... } 

Beware that you'll still have a tricky problem, you are reading a half-written file. The other process flushes data to the file at random points in time, you may well read only half a line of text. YMMV.

like image 191
Hans Passant Avatar answered Sep 21 '22 09:09

Hans Passant


If you want to open the file read-only, try this:

using (TextReader reader     = new StreamReader(File.OpenRead(Path.Combine(client._WorkLogFileLoc, "dump.txt"))))  {               //do stuff  }  

Notice the call to File.OpenRead().

like image 20
Jay Riggs Avatar answered Sep 19 '22 09:09

Jay Riggs