Home >Backend Development >C++ >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:
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!