开发者

How can I read a file that is in use by another process? [duplicate]

开发者 https://www.devze.com 2023-01-28 06:49 出处:网络
This question already has answers here: How can I read a file even when getting an "in use by another process" exception?
This question already has answers here: How can I read a file even when getting an "in use by another process" exception? 开发者_开发技巧 (4 answers) Closed 6 years ago.

I need to read a file that is in use by another process. How can I achieve that in C#?

Thanks!


If the other process put an exclusive lock on the file, then you don't get to read it. The other process locked the file for a reason; do not try to defeat the other program. If you think the other program is locking the file unnecessarily, take it up with the author of the other program.

If they put a non-exclusive lock on the file, then request shared access to the file rather than requesting exclusive access.


If you only need to have read access to the file, you can try the following:

using (var stream = File.Open("log.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var reader = new StreamReader(stream))
{
    // Actions you perform on the reader.
}

Code taken from this post.


One way to access a locked file is to use the volume shadow copy service.

It should be relatively easy to port this code from VB.Net to C#, and to modify it to suit your needs.

You should be hesitant to use this solution, for the reasons Eric Lippert mentions in his answer.


Getting around file access protection in Windows to view an active logfile read-only <-- this may help

0

精彩评论

暂无评论...
验证码 换一张
取 消