Home >Backend Development >C++ >How Can I Read a File Locked by Another Process in C#?

How Can I Read a File Locked by Another Process in C#?

Barbara Streisand
Barbara StreisandOriginal
2025-01-16 15:43:09587browse

How Can I Read a File Locked by Another Process in C#?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn