In the following code I get the error \"stream was not writable\":
class Class1
{
private static void Main()
{
FileStream fs = new F
Do not close the StreamReader. Just comment the line below and it will work.
r.Close();
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.
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();
r.Close();
There's your problem after you read. The close() methods close the underlying stream.
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();
}