FileStream with locked file

我的未来我决定 提交于 2019-12-17 21:05:15

问题


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!


回答1:


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.




回答2:


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.




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



回答4:


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 !



来源:https://stackoverflow.com/questions/6035302/filestream-with-locked-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!