Home >Backend Development >C++ >How Can I Read and Write to the Same File Simultaneously in C#?

How Can I Read and Write to the Same File Simultaneously in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-06 06:43:42350browse

How Can I Read and Write to the Same File Simultaneously in C#?

Concurrently Reading and Writing Files in C#

When working with files in C#, you may encounter scenarios where you need to perform both read and write operations on the same file. However, simply creating separate StreamReader and StreamWriter instances like in the following code won't suffice:

static void Main(string[] args)
{
    StreamReader sr = new StreamReader(@"C:\words.txt");
    StreamWriter sw = new StreamWriter(@"C:\words.txt");
}

To achieve both read and write operations on a file, you must use a single stream that supports both access modes. Here's how you can do it:

FileStream fileStream = new FileStream(
      @"c:\words.txt", FileMode.OpenOrCreate, 
      FileAccess.ReadWrite, FileShare.None);

The FileStream constructor is initialized with the following parameters:

  • FilePath: The path to the file to be accessed.
  • FileMode: Specifies how the file is opened or created. In this case, FileMode.OpenOrCreate is used, which opens the file if it exists or creates it if it doesn't.
  • FileAccess: Specifies the access mode for the file. FileAccess.ReadWrite allows both reading and writing.
  • FileShare: Indicates how the file can be shared with other processes. FileShare.None means that the file cannot be shared.

Once you have created the FileStream instance, you can use it to perform both read and write operations on the file.

The above is the detailed content of How Can I Read and Write to the Same File Simultaneously 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