Open file ReadOnly

C#File Io

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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().

Solution 3 - C#

You can set the file attribute by calling File.SetAttributes

string path = Path.Combine(client._WorkLogFileLoc, "dump.txt");
FileAttributes curAttributes = File.GetAttributes(path);
File.SetAttributes(path, curAttributes | FileAttributes.ReadOnly);

Solution 4 - C#

Per https://docs.microsoft.com/en-us/dotnet/api/system.io.file.openread?redirectedfrom=MSDN&view=netcore-3.1#System_IO_File_OpenRead_System_String_ File.OpenRead enables read shared access not read/write. This prevents the "other process" from being able to close/reopen/write more data as xbonez wants to permit. hans-passant addresses what was requested.

Per the referenced documentation: This method is equivalent to the FileStream(String, FileMode, FileAccess, FileShare) constructor overload with a FileMode value of Open, a FileAccess value of Read and a FileShare value of Read.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionxbonezView Question on Stackoverflow
Solution 1 - C#Hans PassantView Answer on Stackoverflow
Solution 2 - C#Jay RiggsView Answer on Stackoverflow
Solution 3 - C#The Scrum MeisterView Answer on Stackoverflow
Solution 4 - C#Ira GrollmanView Answer on Stackoverflow