73

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123

6 Answers6

80

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

FileStream fileStream = new FileStream(
      @"c:\words.txt", FileMode.OpenOrCreate, 
      FileAccess.ReadWrite, FileShare.None);
MikeW
  • 5,442
  • 32
  • 42
  • 10
    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 Apr 08 '09 at 04:56
  • @ScottS: I agree as far as the ReadWrite is necessary as you can let the constructor figure out the sharing mode. – Samuel Apr 08 '09 at 04:58
  • Thank you both! you really helped me! – Yehonatan Jan 03 '14 at 05:10
68

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");
    }
  • 14
    @Copperpot: Check the requirements from the question. Doesn't say anything about locking. Also, it doesn't say anything about hard drive crashes or meteor strikes interrupting as well. –  Sep 25 '12 at 17:47
  • 1
    I think the question implies 'at the same time.' – John Atwood May 23 '13 at 21:26
  • 4
    @JohnAtwood You know what they say about assumptions. He never did select a correct answer, so we will never *really* know. –  May 23 '13 at 21:34
  • @Copperpot: My solution isn't your solution, your problem is different or at a minimum more explained than the OP, however saying my answer will fail is incorrect. You might be using it wrong, but that's more of an issue with you than with the answer. –  Jan 17 '14 at 20:50
37
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
  • 8,195
  • 3
  • 26
  • 48
2

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.

Community
  • 1
  • 1
mbarthelemy
  • 10,915
  • 4
  • 37
  • 40
1

you can try this:"Filename.txt" file will be created automatically in the bin->debug folder everytime you run this code or you can specify path of the file like: @"C:/...". you can check ëxistance of "Hello" by going to the bin -->debug folder

P.S dont forget to add Console.Readline() after this code snippet else console will not appear.

TextWriter tw = new StreamWriter("filename.txt");
        String text = "Hello";
        tw.WriteLine(text);
        tw.Close();

        TextReader tr = new StreamReader("filename.txt");
        Console.WriteLine(tr.ReadLine());
        tr.Close();
1

Made an improvement code by @Ipsita - for use asynchronous read\write file I/O

readonly string logPath = @"FilePath";
...
public async Task WriteToLogAsync(string dataToWrite)
{
    TextReader tr = new StreamReader(logPath);
    string data = await tr.ReadLineAsync();
    tr.Close();

    TextWriter tw = new StreamWriter(logPath);
    await tw.WriteLineAsync(data + dataToWrite);
    tw.Close();
}
...
await WriteToLogAsync("Write this to file");
Anonimys
  • 377
  • 1
  • 4
  • 11