Search code examples
c#io

File Read-only access irrespective of locks (C#)


How do I open (using c#) a file that is already open (in MS Word, for instance)? I thought if I open the file for read access e.g.

FileStream f= new FileStream('filename', FileMode.Open, FileAccess.ReadWrite);

I should succeed, but I get an exception:

"the process cannot access the file because it is locked ..."

I know there must be a way to read the file irrespective of any locks placed on it, because I can use windows explorer to copy the file or open it using another program like Notepad, even while it is open in WORD.

However, it seems none of the File IO classes in C# allows me to do this. Why?


Solution

  • You want to set FileAccess=Read and FileShare=ReadWrite. Here is a great article on this (along with an explanation of why):

    http://coding.infoconex.com/post/2009/04/How-do-I-open-a-file-that-is-in-use-in-C.aspx