I have the following code:
try
{
FileStream FS = new FileStream(this.InFile, FileMode.Open, FileAccess.Read);
return "";
}
catch (FileNotFoundException ex)
{
return ex.Message;
}
finally
{
FS.Close();
FS.Dispose();
}
but when I compile it I get an error saying that: the name ‘FS’ doesn’t exist in the current context.
so I put a FileStream declaration at the top before the try ..catch block like this
FileStream FS;
try
{
FileStream FS = new FileStream(this.InFile, FileMode.Open, FileAccess.Read);
return "";
}
catch (FileNotFoundException ex)
{
return ex.Message;
}
finally
{
FS.Close();
FS.Dispose();
}
but when I compile I get an error saying use of unassigned variable FS and it points to the finally block.
now I understand both errors and why I am getting them but I don’t know how to code it so that I try the code and catch the errors if there are any.
any help would be appreciated – thanks!
What would happen if a FileNotFoundException were thrown? Then you’d get to the finally clause (FS.Close() and FS.Dispose()) but FS wasn’t initialized! What you should do is initialize FS to null and in the finally clause add an if statement checking the FS is not null