Is it ok to dispose or close an object before you reach the end of a using block?
I was writing a program that would read a log file and write lines of interest into a new file. If something comes up that invalidates the data, the new file gets deleted. I just wanted to make sure that what I did is acceptable.
e.g.
//...
using(StreamReader log = File.OpenText(logfilename))
{
using(StreamWriter output = File.CreateText(outputfilename))
{
string line;
while((line = log.ReadLine()) != null)
{
if(!BadLine(line)) //line isn't bad
output.WriteLine(line);
else
{
output.Close();
File.Delete(outputfilename);
break;
}
}
}
}
(this was written on the fly so it might have errors :) )
Anyway, from what I could understand, the using block ensures that the object is disposed at the end of the block. I'm not sure how or when but I guess it just calls the Dispose method. I guess my underlying question turns out to be:
Is calling Dispose on a closed or disposed (unusable) object good practice?

1 answers
using cleans up the file resources. it is a bad idea to delete it inside the using block. use a flag instead to signify whether you need to delete the file, after it exits the using block. depending on how the file is created it may be locked so attempting to delete it may throw an exception.
bool markedForDeletion = false;
using ( Stream s = File.Create("foo.txt") ) {
markedForDeletion = true;
}
if(markedForDeletion) {
File.Delete("foo.txt");
}
answered 2 years ago by:
2309
Ok so deleting the file within the block, bad form, gotcha.
But in the more general case, disposing/closing the stream within the block (for whatever the reason), I'm thinking bad form as well but does it still produce perfectly valid code?
answered 2 years ago by:
538
the using statement is purely a syntax of C#. when it compiles to msil it writes it out by hand (placing the close / dispose in a try / catch / finally statement), so there is absolutely no need to call close if you're using a using statement (because it will ultimately be called twice). I'm sure calling close twice, or dispose twice isnt going to hurt but I don't think its necessary.
answered 2 years ago by:
2309
This post was imported from csharpfriends, if you have a similiar question please ask it again.
All previous members have been migrated, hope you enjoy the new platform!