如何管理DirectoryInfo写/读异常?

时间:2015-11-05 08:25:59

标签: c# wpf

如何管理DirectoryInfo写/读异常?

 DirectoryInfo di = new DirectoryInfo(tbKeresesHelye.Text);
 foreach (var f in di.GetFiles("*", SearchOption.AllDirectories))
 {
   richTextBox1.Text = richTextBox1.Text + f.Directory + "\\" + f.Name + " >> " + f.Length + "\n";
 }

1 个答案:

答案 0 :(得分:0)

如果我理解正确:

string address = "D:";
DirectoryInfo di = new DirectoryInfo(address);
try
  {
     foreach (var f in di.GetFiles("*", SearchOption.AllDirectories))
     {         
        richTextBox1.Document.Blocks.Clear();
        richTextBox1.Document.Blocks.Add(new Paragraph(new Run(f.DirectoryName + f.Name + " >> " + f.Length + "\n")));
     }
   }
catch (Exception ex)
   {
       richTextBox1.Document.Blocks.Add(new Paragraph(new Run(ex.Message)));
   }

仅为了您的信息,这是异常处理的好习惯:

  • 最确切的例外
  • 不太确切的例外
  • 常见例外

并使用不带标识符的throw关键字来保留原始关键字 这样的异常细节:

catch (DivideByZeroException ex)
{
    throw;
}
catch (InvalidOperationException ex)
{
    throw;
}
catch (Exception ex)
{
    throw;
}
相关问题