I want to both read from and write to a file. This doesn't work.
static void Main(string[] args)
{
StreamReader sr = new StreamReader(@"C:\words.txt");
StreamWriter sw = new StreamWriter(@"C:\words.txt");
}
How can I both read from and write to a file in C#?
You need a single stream, opened for both reading and writing.
The key thing is to open the file with the FileAccess.ReadWrite flag. You can then create whatever Stream/String/Binary Reader/Writers you need using the initial FileStream.
Don't forget the easy route:
This thread seems to answer your question : simultaneous-read-write-a-file
Basically, what you need is to declare two FileStream, one for read operations, the other for write operations. Writer Filestream needs to open your file in 'Append' mode.