How to both read and write a file in C#

Hey picture Hey · Mar 3, 2009 · Viewed 160.8k times · Source

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#?

Answer

MikeW picture MikeW · Mar 3, 2009

You need a single stream, opened for both reading and writing.

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