Is this OK? (.Net 4.5)

try
{
While (line != null)
{
}
sr.Close();
}
catch
{
// blah Do nothing
}


I feel like there is something wrong with my pattern here. My concern is that when there is a file exception, does the stream get closed properly? I was taught to use using to set the stream, but Code Analysis tool does not like it. Perhaps there is something else. It seems to read the file OK, but I remember needing to use File stream and stream reader in the past... Was there a good reason for combining the two?

• You need to close your stream in the finally block. Why does your code analysis tool not like the using statement? – Vsevolod Goloviznin Dec 11 '14 at 14:39
• I think it is when I use nested using statements where this code is not an example of that. So In the finally block... yes but that means I need to... OK I think I have it. Thanks. – amalgamate Dec 11 '14 at 14:43
• So that means I also need to move the initialization of the SR outside the try block. – amalgamate Dec 11 '14 at 14:46
• Yes. What tool do you use? Multiple using statements should be ok – Vsevolod Goloviznin Dec 11 '14 at 14:47
• I guess you can ask a new question with the code that produces it to get some clarification on reasons behind usch behavior of the tool – Vsevolod Goloviznin Dec 11 '14 at 14:57

You always need to dispose of objects in the finally close to ensure that they are disposed correctly.

StreamReader sr = null;
try
{
While (line != null)
{
}
}
catch
{
// blah Do nothing
}
finally
{
if (sr != null)
{
sr.Close();
}
}

• Error: Use of unassigned local variable SR in finally block. I can assign null at the first line? – amalgamate Dec 11 '14 at 14:47
• Yeah, I've updated the code. I've also included the check in the finally just in case StreamReader will not be initialized. – Vsevolod Goloviznin Dec 11 '14 at 14:48

I know there is already an accepted answer here, but have you ever utilized the using statement? This statement will automatically handle all of your disposal for you. And yes, it will take care of it on exceptions. Check out the link HERE and my example below.

try
{
{
While (line != null)
{

• Interesting. I don't receive that warning when using it, but I will have to keep an eye out for sure. Never had any actual errors due to it, I know that much! Thanks for the +1 though! – Volearix Dec 16 '14 at 14:19