-
Notifications
You must be signed in to change notification settings - Fork 369
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Chapter 09. Disposing of file resources #90
Comments
Good point. I will move it outside the if statement. I have added an errata: |
Some addition. In section "Simplifying disposal by using the using statement" (pp. 385,386) there are two code blocks: using (FileStream file2 = File.OpenWrite(Path.Combine(path, "file2.txt")))
{
using (StreamWriter writer2 = new StreamWriter(file2))
{
...
} // automatically calls Dispose if the object is not null
} // automatically calls Dispose if the object is not null and simplified variant: using FileStream file2 = File.OpenWrite(Path.Combine(path, "file2.txt"));
using StreamWriter writer2 = new(file2);
... They are actually not equal. The difference is in a life-scope of the variables. In the first case In the second case both variables live within entire outer code block even if not used anymore. So it might be necessary to manually perform some operations. E.g. if someone wants to read "file2.txt" after writing, they will need to explicitly close the streams: writer2.Close();
file2.Close();
File.ReadAllText(Path.Combine(path, "file2.txt")); I'm sure you're aware of this behaviour, but it took some time for me to realize why seemingly proper code causes exceptions. |
One more thing about Stream decompressor = new GZipStream(file,CompressionMode.Decompress);
using (decompressor)
{
...
} In the documentation MS writes:
|
There's a code on pp. 383, 384:
Why is
xmlFileStream
disposal nested in(xml != null)
check? If I'm not mistaken, theoretically an exception can occur insideXmlWriter.Create
. In that casexml
will remainnull
, thereforexmlFileStream
will not be disposed.The text was updated successfully, but these errors were encountered: