If the compiler can see any route through the software such that the variable does not get a value, it complains. Such a route exists:
FileStream fStream;
StreamWriter sWriter;
try
{
fStream = new FileStream(strFileName, FileMode.Append);
This line causes an exception -
fStream
is not modified.
These lines are skipped:
sWriter = new StreamWriter(fStream);
sWriter.WriteLine(strData);
}
Execution continues here:
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Then the
finally
block is executed:
finally
{
This is the first reference to
sWriter
since it was declared.
sWriter.Close();
sWriter.Dispose();
This is the first reference to
fStream
since it was declared.
fStream.Close();
fStream.Dispose();
}
[edit]
Setting it to
null
gets rid of the compilation problem, but introduces another: your
finally
block will cause an exception if your
try
/
catch
is triggered.
You need to check for null in each before you try to Close or Dispose. I would suggest rewriting this as:
private void AppendData(string strData, string strFileName)
{
try
{
using (FileStream fStream = new FileStream(strFileName, FileMode.Append))
{
using (StreamWriter sWriter = new StreamWriter(fStream))
{
sWriter.WriteLine(strData);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
- OriginalGriff[/edit]