Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
177 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...