1 year ago
#375510
floretti
EnumerateDirectories() can't find part of a path
I'm going through thousands of files in a network path reporting their size and modified date however, my loop constantly stops at the error below despite the folder being existing and accessible.
Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '\\ServerName\Folder\Subfolder'.
This is a snippet of the code block I'm using, which is already done to avoid some other errors I was facing before with access denied but the error happens when I loop over the returned IEnumerable. I don't understand how an EnumerateDirectories and EnumerateFiles can return a list of paths but tell me that the it can't find part of the path it returned in the first place.
public static IEnumerable<string> SafeEnumerateFiles(string path, string searchPattern, SearchOption searchOpt)
{
try
{
var dirFiles = Enumerable.Empty<string>();
if (searchOpt == SearchOption.AllDirectories)
{
dirFiles = Directory.EnumerateDirectories(path)
.SelectMany(x => SafeEnumerateFiles(x, searchPattern, searchOpt));
}
return dirFiles.Concat(Directory.EnumerateFiles(path, searchPattern));
}
catch (UnauthorizedAccessException ex)
{
return Enumerable.Empty<string>();
}
}
I would be very happy to simply skip these problematic folders but not sure how. Any help would be very much appreciated.
UPDATE 1:
I'm getting the exception on the line:
dirFiles = Directory.EnumerateDirectories(path) .SelectMany(x => SafeEnumerateFiles(x, searchPattern, searchOpt));
UPDATE 2:
Sorry, I missed the "catch unauthorized access exception" and removed that specific exception so my code skips through all exceptions but the problem still stands and it would be good to understand how to get rid of the "could not find part of the path" issue.
c#
file-io
enumerate
0 Answers
Your Answer