如何管理DirectoryInfo写入/读取异常

本文关键字:写入 读取 异常 DirectoryInfo 何管理 管理 | 更新日期: 2023-09-27 18:20:34

如何管理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";
 }

如何管理DirectoryInfo写入/读取异常

如果我理解正确:

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;
}