How to Read and Write to a File in C#
When working with files in C#, you often need to both read from and write to them. However, simply creating a StreamReader and StreamWriter for the same file will not work, as the file will be opened in read-only mode.
To read and write to a file simultaneously, you need to use a single stream that is opened for both operations. This can be achieved using the FileStream class.
FileStream fileStream = new FileStream( @"c:\words.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
The FileStream constructor takes the following arguments:
In this case, we are opening the file in OpenOrCreate mode, which means that the file will be created if it does not already exist. We are also opening the file with ReadWrite access, which means that we can both read from and write to the file. Finally, we are specifying that the file should not be shared with other processes.
Once you have created a FileStream, you can use it to read from and write to the file using the Read and Write methods, respectively.
Example
The following example shows how to read from and write to a file using a FileStream:
using System; using System.IO; class Program { static void Main() { // Open the file in read/write mode. FileStream fileStream = new FileStream( @"c:\words.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); // Read the file. StreamReader reader = new StreamReader(fileStream); string line = reader.ReadLine(); while (line != null) { Console.WriteLine(line); line = reader.ReadLine(); } // Write to the file. StreamWriter writer = new StreamWriter(fileStream); writer.WriteLine("This is a test."); // Close the file. fileStream.Close(); } }
This example will open the file "words.txt" in read/write mode. It will then read the file and print its contents to the console. Finally, it will write the string "This is a test." to the file.
The above is the detailed content of How to Simultaneously Read and Write to a File in C#?. For more information, please follow other related articles on the PHP Chinese website!