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
精彩评论