Read and Write to a File Simultaneously in C#
When working with files, it's common to encounter the need to both read and write to a file. However, the following code snippet attempts to do this but fails:
static void Main(string[] args) { StreamReader sr = new StreamReader(@"C:\words.txt"); StreamWriter sw = new StreamWriter(@"C:\words.txt"); }
This code will fail because it uses separate streams for reading and writing, which is not allowed for the same file without explicitly specifying streams for both operations and managing locks.
To read and write to a file simultaneously, you need to use a single stream that is open for both reading and writing. This can be achieved using the FileStream class:
FileStream fileStream = new FileStream( @"c:\words.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
The FileMode.OpenOrCreate parameter specifies that the file should be opened or created if it does not exist.
The FileAccess.ReadWrite parameter specifies that the file should be opened for both reading and writing.
The FileShare.None parameter specifies that no other processes should be allowed to read or write to the file while it is open.
Once you have created the FileStream, you can use it to read and write to the file using the Read() and Write() methods, respectively.
The above is the detailed content of How Can I Simultaneously Read and Write to a File in C#?. For more information, please follow other related articles on the PHP Chinese website!