Reputation: 7696
I get an error when I'm trying to get a DirectoryInfo
because there is some read only file and folder.
How can I skip them?
var dirinfo = new DirectoryInfo(Path_Tb_Path.Text);
var entries = dirinfo.GetFileSystemInfos("**", SearchOption.AllDirectories);
Upvotes: 0
Views: 576
Reputation: 1038770
In .NET 4.0 you could use the EnumerateFileSystemInfos
method. For example you could write the following recursive method which will swallow the UnauthorizedAccessException
for some files and only include those files in the result for which you have permission to access:
public static IEnumerable<FileSystemInfo> SafeGetFileSystemInfosRecursive(DirectoryInfo directory, string searchPattern)
{
try
{
return directory
.EnumerateFileSystemInfos(searchPattern)
.Concat(
directory
.EnumerateDirectories()
.SelectMany(x => SafeGetFileSystemInfosRecursive(x, searchPattern))
);
}
catch (UnauthorizedAccessException)
{
return Enumerable.Empty<FileSystemInfo>();
}
}
and then call the method like that:
var dirInfo = new DirectoryInfo(Path_Tb_Path.Text);
FileSystemInfo[] entries = SafeGetFileSystemInfosRecursive(dirInfo, "**").ToArray();
Upvotes: 1