David Degea
David Degea

Reputation: 1398

Cannot write to file after reading

In the following code I get the error "stream was not writable":

class Class1
{
    private static void Main()
    {
        FileStream fs = new FileStream("C:\\fFile.txt", 
                              FileMode.OpenOrCreate, 
                              FileAccess.ReadWrite, 
                              FileShare.ReadWrite);

        StreamReader r = new StreamReader(fs);
        string t = r.ReadLine();
        r.Close();
        Console.WriteLine(t);

        StreamWriter w = new StreamWriter(fs);
        w.WriteLine("string");
        w.Flush();
        w.Close();
        fs.Close();

    }
}    

The error occurs at this line StreamWriter w = new StreamWriter(fs);

Why is this?

Upvotes: 3

Views: 7169

Answers (5)

Oscar Cabrero
Oscar Cabrero

Reputation: 4169

You'll have to re-open the file since the read closes it:

FileStream fs = new FileStream("C:\\test.txt", 
                        FileMode.OpenOrCreate, 
                        FileAccess.ReadWrite, 
                        FileShare.ReadWrite);
using (StreamReader r = new StreamReader(fs))
{
    string t = r.ReadLine();
    r.Close();
    Console.WriteLine(t);
}

fs = new FileStream("C:\\test.txt", 
            FileMode.OpenOrCreate, 
            FileAccess.ReadWrite, 
            FileShare.ReadWrite);

using (StreamWriter w = new StreamWriter(fs))
{
    w.WriteLine("string");
    w.Flush();
    w.Close();
}
fs.Close();

Upvotes: 1

jmisra
jmisra

Reputation: 21

Do not close the StreamReader. Just comment the line below and it will work.

 r.Close();

Upvotes: 0

MGZero
MGZero

Reputation: 5963

r.Close(); 

There's your problem after you read. The close() methods close the underlying stream.

Upvotes: 2

Jay
Jay

Reputation: 6294

Dont close the first StreamWriter, it will close the underlying stream. And use using statements as Oscar suggests.

using (FileStream fs = new FileStream("C:\\temp\\fFile.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
    StreamReader r = new StreamReader(fs);
    string t = r.ReadLine();

    Console.WriteLine(t);

    StreamWriter w = new StreamWriter(fs);
    w.WriteLine("string");
    w.Close();
    r.Close();
    fs.Close();
}

Upvotes: 0

rerun
rerun

Reputation: 25495

from msdn

Closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.

So the stream you try to write to is invalid you need to reopen the stream and reopen the file.

Upvotes: 4

Related Questions