FileStream with locked file
Asked Answered
T

4

19

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!

Tipper answered 17/5, 2011 at 18:19 Comment(1)
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.Pickaxe
D
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.

Dulles answered 17/5, 2011 at 18:22 Comment(0)
G
8
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.

Gastrin answered 17/5, 2011 at 18:56 Comment(0)
L
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);
Lipman answered 23/3, 2016 at 22:28 Comment(0)
S
-3

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 !

Superimpose answered 17/8, 2012 at 14:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.