gpt4 book ai didi

c# - 忽略 Directory.EnumerateFiles 的异常,跳过那些文件

转载 作者:行者123 更新时间:2023-11-30 12:54:52 34 4
gpt4 key购买 nike

在枚举时我想跳过/忽略异常。

我尝试在选择器中添加一个 try catch:

static IEnumerable<string> GetSafeAllFiles
(string path, string searchPattern, SearchOption searchOption = SearchOption.AllDirectories)
{
return Directory.EnumerateFiles(path, searchPattern, searchOption)
.Select(f =>
{
try
{
return f;
}
catch (Exception e)
{
return string.Empty;
}
});
}

我尝试使用来自 accepted answer 的解决方案:

var test23 = Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories)
.SkipExceptions().Take(100);

没有结果,因为它会在第一个错误后停止。所以我尝试实现我自己的:

static IEnumerable<string> test12(string path, string searchPattern, SearchOption searchOption = SearchOption.AllDirectories)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
if (string.IsNullOrEmpty(searchPattern))
{
throw new ArgumentNullException("searchPattern");
}

Queue<string> stillToProcess = new Queue<string>(new[] { path });

foreach (var dir in Directory.EnumerateDirectories(path))
{
stillToProcess.Enqueue(dir);
}

while (stillToProcess.Count > 0)
{
string currentPath = stillToProcess.Dequeue();
IEnumerable<string> ret = Enumerable.Empty<string>();
try
{
ret = Directory.EnumerateFiles(currentPath, searchPattern);
}
catch (UnauthorizedAccessException e)
{ }
// yield! keyword
foreach (var i in ret) { yield return i; }
}
yield break;
}

但如果有一个错误,它会跳过目录。当我只想跳过错误文件时。

为了测试,可能的解决方案请在 c:\$Recycle.Bin 上进行,因为它是 UnauthorizedAccessException 的最简单来源。

最佳答案

这是我想出的:

public static IEnumerable<FileInfo> EnumerateFilesIgnoreErrors(IEnumerable<FileInfo> files)
{
using (var e1 = files.GetEnumerator())
{
while (true)
{
FileInfo cur = null;

try
{
// MoveNext() can throw an Exception
if (! e1.MoveNext())
break;

cur = e1.Current;

}
catch (Exception ex)
{
Debug.WriteLine(ex);
}

if (cur != null)
{
yield return cur;
}
}
}
}

像这样使用:

var myFiles = new DirectoryInfo(@"C:\")
.EnumerateFiles("*", SearchOption.AllDirectories);

foreach (FileInfo fi in EnumerateFilesIgnoreErrors(myFiles))
{
Debug.WriteLine(fi.Name);
}

你也可以这样使用它:

var myList = EnumerateFilesIgnoreErrors(myFiles).ToList();

适用于“c:\$Recycle.Bin”等
忽略 UnauthorizedAccessException

关于c# - 忽略 Directory.EnumerateFiles 的异常,跳过那些文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52949632/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com