This is a code snippet from lesson 2 in the book ... when I typed it in I thought it would fail, if there was a problem finding the file.
The problem I saw is the StreamReader will try and open the file before the Try statement, so if there is an error it would not be caught.
The book said to put the StreamReader outside the Try Statement, so the finally block can close the file, since it could not see 'tr' if it was declared inside the Try statement.
private void showButton_Click(object sender, EventArgs e)
{
TextReader tr = new StreamReader(locationTextBox.Text);
try
{
displayTextBox.Text = tr.ReadToEnd();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
tr.Close();
}
}
I worked around it by doing this, but would like to know if I missed something in the first go around or if there would be another way to do it.
private void showButton_Click(object sender, EventArgs e)
{
TextReader tr=null;
try
{
tr = new StreamReader(locationTextBox.Text);
displayTextBox.Text = tr.ReadToEnd();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
try
{
tr.Close();
}
catch { }
}
}