开发者

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开发者_如何学Python();

    }
}    

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

Why is this?


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.


r.Close(); 

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


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();


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();
}


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

 r.Close();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜