I’d like to write a log record in case of a failed attempt of a file reading(writing) operation, something like:
try
{
//some file operation, for example:
TextReader tr2 = new StreamReader(nfilepath);
resultN = tr2.ReadLine();
tr2.Close();
}
catch (Exception ex)
{
string recfilepath = "...
string rectoadd = "RecDateTime=" + DateTime.Now.ToString()+ ...+ex.Message.ToString();
File.AppendAllText(recfilepath, rectoadd);
}
Is this a correct way of doing that? What if in the above example the attempt of writing a log record (File.AppendAllText(recfilepath, rectoadd);) fail as well?
Never catch Exception type – by this way you hide program bugs. Catch only expected exception types – in this case, it can be IOException.
Inside catch block, you can add another try-catch block, and report logging error by some another way: Trace, message box etc.