17

I am wondering if it's possible to get a readonly FileStream to a locked file? I now get an exception when I try to read the locked file.

using (FileStream stream = new FileStream("path", FileMode.Open))

Thanks!

SaphuA
  • 2,924
  • 3
  • 36
  • 56
  • The line you show isn't attempting to read a locked file, it is where you are attempting to open a file. Are you creating this file somewhere else? If a lock condition exist you are probably doing something to create that condition. Please show more of the code around the single line you listed. – Cos Callis May 17 '11 at 18:36

4 Answers4

29

You should try another constructor. They are documented at MSDN.

This one looks like a bet:

FileStream Constructor (String, FileMode, FileAccess, FileShare)

MSDN Link

FileAccess

A constant that determines how the file can be accessed by the FileStream object. This gets the CanRead and CanWrite properties of the FileStream object. CanSeek is true if path specifies a disk file.

FileShare

A constant that determines how the file will be shared by processes.

jgauffin
  • 95,399
  • 41
  • 227
  • 352
7
using (FileStream stream = new FileStream("path", FileMode.Open))

That will use the default value for the FileShare argument, FileShare.Read. Which denies any process from writing to the file. That cannot work if another process is writing to the file, you cannot deny a right that was already gained.

You have to specify FileShare.ReadWrite. That might still not work if the other process used FileShare.None, no workaround for that. Beware that getting read access to a file that's being written is troublesome, you don't have a reliable end-of-file indication. The last record or line in the file might have only been partially written.

Hans Passant
  • 873,011
  • 131
  • 1,552
  • 2,371
3

I've used the following which works, however should use with caution as file can be modified while you have it open by another process.

FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read,FileShare.ReadWrite);
Malcolm McCaffery
  • 1,951
  • 1
  • 18
  • 31
-2

You can simply unlock file and read file after it. Just use Handle.exe from Sysinternals , or Unlocker with command line options. They both can unlock file , and you can execute them from your program easily, without leaving your program. (But don't use them for Windows SAM file, it doesn't work with SAM ;) ) Good luck !

Searush
  • 600
  • 1
  • 4
  • 18