I have 2 pieces of code. Take a look at this one.
static void Main(string[] args)
{
using (FileStream fs = new FileStream("temp.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (StreamWriter writer = new StreamWriter(fs))
{
writer.WriteLine("Hello World");
using (StreamReader reader = new StreamReader(fs))
{
Console.WriteLine(reader.ReadToEnd());
} // Line-1
} //Line-2 -> System.ObjectDisposedException: 'Cannot access a closed file.'
}
}
At the Line-2 I get System.ObjectDisposedException occurs. Why do I get this exception here?
After a little bit of thinking I thought that the exception occurred at Line-2 because the Stream associated with reference 'fs' is already closed at Line-1. And at Line-2 it is trying to close the same stream again. And this answer made sense. Hence, I thought I had found the right answer to my question but then I tried something a little bit different.
Now look at this piece of code.
static void Main(string[] args)
{
using (FileStream fs = new FileStream("temp.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (StreamReader reader = new StreamReader(fs))
{
Console.WriteLine(reader.ReadToEnd());
using (StreamWriter writer = new StreamWriter(fs))
{
writer.WriteLine("Hello World");
} // Line-1
} // Line-2 -> No Exception occurred.
}
}
In this piece of code I didn't get any exception. Even though I am doing the same thing again. Here also the stream associated with reference 'fs' is already closed at Line-1 and it is also trying to close the stream at Line-2.
So why didn't I get any exception here?
My question is different from this Is there any way to close a StreamWriter without closing its BaseStream? because I am trying to do the same thing with the second code and despite the fact (in second code) that using statement already closed the base stream (fs) in Line-1. I still don't get any exception in Line-2.
Since @mjwills and @evk said the exception occurred because of flushing the contents of the stream after the file had been closed.
I tried this.
static void Main(string[] args)
{
using (FileStream fs = new FileStream("temp.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (StreamWriter writer = new StreamWriter(fs))
{
writer.WriteLine("Hello World");
writer.Flush(); // Flushed the contents explicitly.
using (StreamReader reader = new StreamReader(fs))
{
Console.WriteLine(reader.ReadToEnd());
} // Line-1
} // Line-2 -> System.ObjectDisposedException: 'Cannot access a closed file.'
}
}
And the result is same I still have that exception even though I have explicitly flushed the contents. Please help.