本文介绍了在LINQ C#拉手System.UnauthorizedAccessException的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用下面的LINQ查询,以获得目录列表。我得到一个错误(System.UnauthorizedAccessException的是由用户代码未处理)。如何加载只对那些我曾访问的目录。
I am using below LINQ query to get the directory list. I am getting an error (System.UnauthorizedAccessException was unhandled by user code). How to load only the directories to which I have access to.
var files = from f in System.IO.Directory.GetDirectories(@"\\testnetwork\abc$",
"*.*",
SearchOption.AllDirectories)
select System.IO.Path.GetDirectoryName(f);
错误:
Error:
访问路径\testnetwork\abc $ \DemoFolder\'被拒绝。
Access to the path '\testnetwork\abc$\DemoFolder\' is denied.
推荐答案
使用捕捉赶上UnauthorizedAccessException。
Catch the UnauthorizedAccessException using Catch. .
string[] directories = Directory.EnumerateDirectories(@"\\testnetwork\abc$","*.*", SearchOption.AllDirectories).Catch(typeof(UnauthorizedAccessException)).ToArray();
ExceptionExtensions:
ExceptionExtensions:
static class ExceptionExtensions
{
public static IEnumerable<TIn> Catch<TIn>(
this IEnumerable<TIn> source,
Type exceptionType)
{
using (var e = source.GetEnumerator())
while (true)
{
var ok = false;
try
{
ok = e.MoveNext();
}
catch(Exception ex)
{
if (ex.GetType() != exceptionType)
throw;
continue;
}
if (!ok)
yield break;
yield return e.Current;
}
}
}
这篇关于在LINQ C#拉手System.UnauthorizedAccessException的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!