本文介绍了有没有从Directory.EnumerateFiles的异常中恢复的一种方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET 4中,有此目录.EnumerateFiles()方法递归似乎得心应手。
但是,如果发生异常递归中,我怎么能继续/恢复从并继续枚举文件的休息吗?

 尝试
{
  var中的文件,从文件=在Directory.EnumerateFiles(C:\\
                           *。*,SearchOption.AllDirectories)
              选择新
              {
                文件=文件
              };

  Console.WriteLine(files.Count()的ToString());

}
赶上(UnauthorizedAccessException UEX)
{
  Console.WriteLine(uEx.Message);
}
赶上(PathTooLongException ptlEx)
{
  Console.WriteLine(ptlEx.Message);
}
 

解决方案

我没有找到一个解决的办法。通过使用堆栈推枚举结果,可以确实处理的异常。这里有一个code段:(由<一个启发href="http://www.$c$cguru.com/columns/vb/article.php/c17971/Enumerating-Files-and-Directories-in-VB-2010.htm"相对=nofollow>这篇文章)

 名单,其中,串&GT;结果=新名单,其中,串&GT;();
字符串开始=C:\\;
results.Add(开始);
堆叠&LT;字符串&GT;堆栈=新的堆栈&LT;字符串&GT;();

做
{
  尝试
  {
    VAR迪尔斯= dir命令在Directory.EnumerateDirectories(
                     开始,*。*,SearchOption.TopDirectoryOnly)
                选择目录;

    Array.ForEach(dirs.ToArray(),stack.Push);
    开始= stack.Pop();
    results.Add(开始);
  }
  赶上(UnauthorizedAccessException前)
  {
    Console.WriteLine(ex.Message);
    开始= stack.Pop();
    results.Add(开始);
  }

}而(stack.Count!= 0);

的foreach(在结果字符串的文件)
{
  Console.WriteLine(文件);
}
 

In .NET 4, there's this Directory.EnumerateFiles() method with recursion that seems handy.
However, if an Exception occurs within a recursion, how can I continue/recover from that and continuing enumerate the rest of the files?

try
{
  var files = from file in Directory.EnumerateFiles("c:\\",
                           "*.*", SearchOption.AllDirectories)
              select new
              {
                File = file
              };

  Console.WriteLine(files.Count().ToString());

}
catch (UnauthorizedAccessException uEx)
{
  Console.WriteLine(uEx.Message);
}
catch (PathTooLongException ptlEx)
{
  Console.WriteLine(ptlEx.Message);
}
解决方案

I did found a solution to this. By using a stack to push the enumeration results, one can indeed handle the exceptions. Here's a code snippet: (inspired by this article)

List<string> results = new List<string>();
string start = "c:\\";
results.Add(start);
Stack<string> stack = new Stack<string>();

do
{
  try
  {
    var dirs = from dir in Directory.EnumerateDirectories(
                     start, "*.*", SearchOption.TopDirectoryOnly)
                select dir;

    Array.ForEach(dirs.ToArray(), stack.Push);
    start = stack.Pop();
    results.Add(start);
  }
  catch (UnauthorizedAccessException ex)
  {
    Console.WriteLine(ex.Message);
    start = stack.Pop();
    results.Add(start);
  }

} while (stack.Count != 0);

foreach (string file in results)
{
  Console.WriteLine(file);
}

这篇关于有没有从Directory.EnumerateFiles的异常中恢复的一种方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 05:18