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