带有锁定文件的 FileStream
我想知道是否可以将只读 FileStream 获取到锁定的文件? 现在,当我尝试读取锁定的文件时,出现异常。
using (FileStream stream = new FileStream("path", FileMode.Open))
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该尝试另一个构造函数。它们记录在 MSDN 中。
这看起来像是一个赌注:
MSDN 链接
FileAccess
文件共享
You should try another constructor. They are documented at MSDN.
This one looks like a bet:
MSDN Link
FileAccess
FileShare
这将使用 FileShare 参数的默认值 FileShare.Read。这拒绝任何写入文件的过程。如果另一个进程正在写入该文件,则该方法不起作用,您不能否认已经获得的权利。
您必须指定 FileShare.ReadWrite。如果其他进程使用 FileShare.None,这可能仍然不起作用,没有解决方法。请注意,对正在写入的文件进行读取访问很麻烦,您没有可靠的文件结束指示。文件中的最后一条记录或最后一行可能仅被部分写入。
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.
您可以简单地解锁文件并在其后读取文件。
只需使用 Sysinternals 中的 Handle.exe 或带有命令行选项的 Unlocker 即可。
它们都可以解锁文件,并且您可以轻松地从程序中执行它们,
无需离开您的程序。
(但不要将它们用于 Windows SAM 文件,它不适用于 SAM ;))
祝你好运 !
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 !