记录错误然后将其打印出来

时间:2016-02-18 17:01:35

标签: c# error-handling try-catch

List<string> errorLog = new List<string>();

foreach (DirectoryInfo dir in directories)
{
    try
    {
        dir.Delete(true);
    }
    catch (System.IO.IOException msg)
    {
        code = 5;
        errorLog.Add(String.Concat(dir.FullName, " ", msg.Message));
        Console.WriteLine("Error Removing the directory: {0}", dir.FullName);
    }
}

我有一个for each循环,它将遍历目录列表并删除它们,但保留父目录。如果发生错误,我想记录它。我创建了一个list并在catch中添加了错误。最后,我可以检查错误日志列表的长度,如果它大于零,我可以打印它们。我已经看到他们在catch中调用usingstreamwriter的帖子,但是如果在编写错误日志时发生了什么会发生什么?

我正在做的是不好的做法?如果是这样,我该怎么办?

1 个答案:

答案 0 :(得分:0)

我认为你有正确的想法。有很多解决方案,但最近我尝试将控制台输出重新路由到文件,它工作得很好。关于您的解决方案,它看起来像:

try
{
    FileStream oStream;
    StreamWriter sWriter;
    var oldOut = Console.Out;
    var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    const string outputFileName = "\\errorlog.txt";
    var fullPath = string.Concat(desktopPath, outputFileName);
    Console.SetOut(sWriter);

    foreach (DirectoryInfo dir in directories)
    {
       try
       {
           dir.Delete(true);
       }
       catch(System.IO.IOException msg)
       {
           code = 5;
           errorLog.Add(String.Concat(dir.FullName," ",msg.Message));
           Console.WriteLine("Error Removing the directory: {0}", dir.FullName);
       }
    }
}
catch(Exception e)
{
    //handle error with streams or file
}
finally
{
    //ensures that we close the connections and such
    Console.SetOut(oldOut);
    sWriter.Close();
    oStream.Close();
}

finally块确保如果发生任何未处理的事情,流和文件仍将关闭。