How to both read and write a file in C#

2019-01-02 15:32发布

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

4条回答
呛了眼睛熬了心
2楼-- · 2019-01-02 15:53

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

FileStream fileStream = new FileStream(
      @"c:\words.txt", FileMode.OpenOrCreate, 
      FileAccess.ReadWrite, FileShare.None);
查看更多
倾城一夜雪
3楼-- · 2019-01-02 16:10
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.

查看更多
流年柔荑漫光年
4楼-- · 2019-01-02 16:16

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");
    }
查看更多
裙下三千臣
5楼-- · 2019-01-02 16:19

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.

查看更多
登录 后发表回答