FileStream with locked file

2019-01-20 07:33发布

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!

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-20 07:57

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);
查看更多
劳资没心,怎么记你
3楼-- · 2019-01-20 08:01
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.

查看更多
我命由我不由天
4楼-- · 2019-01-20 08:15

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 !

查看更多
We Are One
5楼-- · 2019-01-20 08:22

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.

查看更多
登录 后发表回答