Maybe it is a trival question, but it's bothering me. And don't shout laud if it is a duplicate - I tried to search, but there are so many questions regarding using that it was hard for me to find the answer.
I've a code like this:
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
using (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("example.txt", FileMode.Create, ISF)))
writeFile.WriteLine("Example");
And my questions are: What happens to my created IsolatedStorageFileStream
, when StreamWriter
is disposed, while leaving using? Will it be also disposed?
Is there any difference in comparison to this code:
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
using (IsolatedStorageFileStream stream = ISF.CreateFile("example.txt"))
using (StreamWriter writeFile = new StreamWriter(stream))
writeFile.WriteLine("Example");
Thanks in advance.
You have a constructor for
StreamWriter
(NET Framework 4.5 only) that allows specifying theleaveOpen
boolean that defines whether your instance takes ownership of the underlying stream or not.If not specified (as in your example, or for previous versions of the framework), by default it's
false
, so closing (or disposing) the instance closes the underlying stream.So there is no difference between both pieces of code you provided.
Once it leaves the using block, Dispose is called.
using Statement (C# Reference)
Use {} always! It makes the intention of your code a lot better. Your code looks like:
You can then see that the StreamWriter is executed in the context of the ISF. If I understand the ISF correctly, the ISF should not be closed when the Streamwriter closes the file. And you could open another File in the ISF Block.
Your stream remains open even though the stream writer is disposed of. You could, for example, open another stream writer and continue writing to the stream.