If I create a stream inside of the try block and an exception is raised does the stream automatically get disposed of? For example:
try
{
Stream stream = response.GetResponseStream();
//Error Occurs
stream.Close();
}
catch
{
//Handle Error
}
If this is not the way to do it can you please suggest an approach?
No, you need to use
finallyOr, wrap your
Streamdeclaration/definition in ausingstatement, which callsClose()automatically:Note that my two examples are not exactly equivalent – in the first, the exception is handled before
steam.Close()is called, in the second the exception is handled after.