Use FileShare.ReadWrite to read locked files
Many applications encounter situations where they need to read files that are currently being modified by other processes. In this case, opening the file using traditional methods often results in a "used by another process" exception. To overcome this limitation, consider using the FileShare.ReadWrite parameter when opening the file. This parameter grants read and write access to the file, allowing other processes to continue writing while your program reads its contents.
The following is an example demonstrating this method in C#:
<code class="language-csharp">FileStream logFileStream = new FileStream("c:\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); StreamReader logFileReader = new StreamReader(logFileStream); while (!logFileReader.EndOfStream) { string line = logFileReader.ReadLine(); // 您的代码在此处 } // 清理 logFileReader.Close(); logFileStream.Close();</code>
By using FileShare.ReadWrite, your program can establish a read-only connection to a file while allowing other processes to modify the file simultaneously. This method provides a convenient solution for applications that need to access frequently updated files.
The above is the detailed content of How Can I Read a File Locked by Another Process in C#?. For more information, please follow other related articles on the PHP Chinese website!