How to both read and write a file in C#
Asked Answered
W

6

76

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

Wangle answered 3/3, 2009 at 9:22 Comment(0)
P
86

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

FileStream fileStream = new FileStream(
      @"c:\words.txt", FileMode.OpenOrCreate, 
      FileAccess.ReadWrite, FileShare.None);
Provence answered 3/3, 2009 at 9:27 Comment(2)
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.Procreant
@ScottS: I agree as far as the ReadWrite is necessary as you can let the constructor figure out the sharing mode.Farrell
P
67

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");
    }
Purplish answered 29/9, 2010 at 11:52 Comment(5)
@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.Purplish
I think the question implies 'at the same time.'Obduliaobdurate
@JohnAtwood You know what they say about assumptions. He never did select a correct answer, so we will never really know.Purplish
@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.Purplish
The memory footprint of this solution can get prohibitively large.Noncontributory
P
39
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.

Procreant answered 8/4, 2009 at 4:54 Comment(0)
B
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.

Beast answered 27/6, 2012 at 11:8 Comment(0)
H
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();
Habituate answered 21/7, 2019 at 17:1 Comment(0)
G
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");
Guilty answered 28/8, 2019 at 22:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.