Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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.

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);

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 !

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top