The first thing you should do is change the method you are using:
var files = from f in System.IO.Directory.EnumerateDirectories(
@"\\testnetwork\abc$",
"*.*",
SearchOption.AllDirectories)
select f;
EnumerateDirectories
works better because it yields the results, and still throws the same exception if it finds a folder where it has no rigths. The fact that it yields the results allows us to compose on top of its output, so if we add an extension method like this:
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;
}
}
}
then we are allowed to write something like this:
var files = from f in System.IO.Directory.EnumerateDirectories(
@"\\testnetwork\abc$",
"*.*",
SearchOption.AllDirectories)
.Catch(typeof(UnauthorizedAccessException))
select f;
and your output should be the expected one while still keeping the Linq expression clean and composable. The idea of the Catch
method is to "swallow" the exception you don't want around without preventing the other ones from happening. It's a draft implementation, but you get the idea.