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
中添加了错误。最后,我可以检查errorLog列表的长度,如果它大于零,则可以打印它们。我看过一些帖子,它们在捕获中将它们分别称为using
和streamwriter
,但是如果在编写错误日志时发生某些情况该怎么办?我正在做的事情被认为是不好的做法吗?如果是,该怎么办?
最佳答案
我认为您有正确的主意。有很多解决方案,但是最近我尝试将控制台输出重新路由到文件,并且效果很好。关于您的解决方案,它看起来像:
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块确保即使发生任何未处理的事件,流和文件仍将关闭。
关于c# - 记录错误,然后将其打印出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35487824/