汇总结果时并行LINQ未经授权的Accessexception



我正在使用LINQ并行搜索以查找模式匹配文件。

public class ParallelLinq
{
    public IList<string> SearchFolders = new List<string>
    {
        @"C:Windows" //can be multiple
    };
    protected virtual IEnumerable<string> GetFiles(string path, string[] searchPatterns, SearchOption searchOption = SearchOption.AllDirectories)
    {
        return searchPatterns.AsParallel()
            .SelectMany(searchPattern =>
            {
                try
                {
                    return Directory.EnumerateFiles(path, searchPattern, searchOption);
                }
                catch (Exception ex) //catch UnauthoizedException/IOExceptions
                {
                    return Enumerable.Empty<string>();
                }
            });
    }
    public IEnumerable<string> Find(IList<string> patterns)
    {
        var testResultFiles = Enumerable.Empty<string>();
        if (!SearchFolders.Any() || !patterns.Any())
        {
            return testResultFiles;
        }
        testResultFiles = SearchFolders.AsParallel().Aggregate(testResultFiles, (current, folder) => current.Union(GetFiles(folder, patterns.ToArray())));
        return testResultFiles;
    }
}

但是,当我尝试评估值时,我正在使用System.UnauthorizedAccessException: Access to the path 'C:WindowsappcompatPrograms' is denied.

var plinq = new ParallelLinq();
var res = plinq.Find(new List<string> { "*.dll" });
Console.WriteLine("Linq Count: " + res.Count());

虽然期望这些例外,但我们如何才能抓住它们并继续前进?

完全例外:

未经手的异常:system.AggregateException:一个或多个错误 发生。---> system.unauthorizedAccessexception:访问路径 'C: Windows AppCompat Programs'被拒绝。在 system.io。 在 system.io.io.filesystemenumoserator 1.AddSearchableDirsToStack(SearchData localSearchData) at System.IO.FileSystemEnumerableIterator 1.movenext()at system.linq.parallel.SelectManyQueryOperator 3.SelectManyQueryOperatorEnumerator 1.Movenext(toutput&amp; 电流元件,对 2& currentKey) at System.Linq.Parallel.PipelineSpoolingTask 2. -spoolingwork()at system.linq.parallel.spoolingtaskbase.work()at at at at system.linq.parallel.querytask.basework(对象未使用) system.linq.parallel.queryTask。&lt;> c。 system.threading.tasks.task.innerinvoke()at at system.threading.tasks.task.execute()---内部异常的结尾 堆栈跟踪---在 system.linq.parallel.queryTaskGroupState.Queryend(boolean userInitiationdispose)at system.linq.parallel.AsynChronousChannelMergeEnumerator 1.MoveNextSlowPath() at System.Linq.Parallel.AsynchronousChannelMergeEnumerator 1.movenext()
在system.linq.parallel.queryopeningenumerator 1.MoveNext() at System.Linq.Enumerable.<UnionIterator>d__67 1.movenext()at system.linq.enumerable.count [tsource](iEnumerable`1 source)

public class ParallelLinq
{
    public IList<string> SearchFolders = new List<string>
    {
        @"C:Windows" //can be multiple
    };
    private static string[] TryGetTopDirectories(string path)
    {
        try
        {
            return Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly);
        }
        catch
        {
            return new string[0];
        }
    }
    private static IEnumerable<string> GetSubfolders(string path, SearchOption searchOption)
    {
        if (searchOption == SearchOption.TopDirectoryOnly)
        {
            return TryGetTopDirectories(path);
        }
        else
        {
            var topFolders = TryGetTopDirectories(path);
            return topFolders.Concat(
                topFolders.SelectMany(subFolder => GetSubfolders(subFolder, searchOption)));
        }
    }
    protected virtual ParallelQuery<string> GetFiles(string path, string[] searchPatterns, SearchOption searchOption = SearchOption.AllDirectories)
    {
        return GetSubfolders(path, searchOption).AsParallel()
            .SelectMany(subfolder =>
            {
                try
                {
                    return searchPatterns.SelectMany(searchPattern => Directory.EnumerateFiles(subfolder, searchPattern)).ToArray();
                }
                catch (Exception ex) //catch UnauthoizedException/IOExceptions
                {
                    return Enumerable.Empty<string>();
                }
            });
    }
    public IEnumerable<string> Find(IList<string> patterns)
    {
        var testResultFiles = Enumerable.Empty<string>();
        if (!SearchFolders.Any() || !patterns.Any())
        {
            return testResultFiles;
        }
        testResultFiles = SearchFolders.AsParallel().Aggregate(testResultFiles, (current, folder) => current.Union(GetFiles(folder, patterns.ToArray())));
        return testResultFiles;
    }
}

似乎是路径'c: windows appcompat programs'正在阻止程序创建文件。可以通过在文件夹本身中添加额外许可来解决。

如何手动向文件夹添加权限

最新更新