我尝试使用递归的内置方法:
public IEnumerable<string> Foo(string path)
{
try
{
foreach (string file in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
{
yield return file;
}
}
catch (Exception)
{ }
}
并收到此错误:
无法使用catch子句在try块的主体中生成值
我如何使用try-catch
以避免崩溃的方法是我没有文件夹权限?
答案 0 :(得分:1)
public IEnumerable<string> Foo(string path)
{
var files = new List<string>();
try
{
files.AddRange(Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories));
}
catch (Exception)
{
// this is bad style. You should catch more specific exceptions
}
return files;
}