views:

5456

answers:

4

I want to both read and write to a file. this dont works

static void Main(string[] args)
        {
            StreamReader sr = new StreamReader(@"C:\words.txt");
            StreamWriter sw = new StreamWriter(@"C:\words.txt");
        }

How do both read and write file in C#?

+16  A: 

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

FileStream fileStream = new FileStream(
      @"c:\words.txt", FileMode.OpenOrCreate, 
      FileAccess.ReadWrite, FileShare.ReadWrite));
MikeW
FileShare.ReadWrite is not neccesary, and is likely undeseriable, it will allow other applications to Read and Write your file while you are using it. Generally FileShare.None is preferred when writing to a file, to prevent others from accessing a file while you work on it.
ScottS
@ScottS: I agree as far as the ReadWrite is necessary as you can let the constructor figure out the sharing mode.
Samuel
Omit the last `)`
+6  A: 
var fs = File.Open("file.name", FileMode.OpenOrCreate, FileAccess.ReadWrite);
var sw = new StreamWriter(fs);
var sr = new StreamReader(fs);

...

fs.Close();
//or sw.Close();

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.

ScottS
+3  A: 

Don't forget the easy route:

    static void Main(string[] args)
    {
        var text = File.ReadAllText(@"C:\words.txt");
        File.WriteAllText(@"C:\words.txt", text + "DERP");
    }
Will