尝试从没有权限的位置添加文件时如何处理UnauthorizedAccessException [英] How to handle UnauthorizedAccessException when attempting to add files from location without permissions
问题描述
我正在尝试通过这种方式从文件夹中获取所有文件:
I am trying to get all files from folder this way:
try
{
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
}
catch (UnauthorizedAccessException)
{
throw;
}
如果我的根文件夹包含用户无权访问的文件夹,则会捕获 UnauthorizedAccessException
,并且我的数组为空,并且所有递归都将失败.
If my root folder contains a folder for which the user doesn't have permission to access, the UnauthorizedAccessException
is caught and my array is empty and all the recursion failed.
如何处理这种情况并确保我的代码未经许可就忽略位置,而是从具有许可权的位置添加文件?
How can I handle this case and insure that my code ignore locations without permission but add the files from location with permissions?
推荐答案
请参见 SafeFileEnumerator 在另一篇文章中.我过去曾经成功使用SafeFileEnumerator代码.当您根本无权访问单个文件时,它可以防止丢失整个枚举,因此您仍然可以遍历可访问的文件.
see SafeFileEnumerator on this other post. I have used the SafeFileEnumerator code in the past with success. It prevents loosing the entire enumeration when you simply don't have access to a single file so you are still able to iterate through the files that you can access.
我拥有的版本与我链接到的版本略有不同,所以让我分享我拥有的版本.
The version I have is slightly different from the one I linked to so let me share the version I have.
public static class SafeFileEnumerator
{
public static IEnumerable<string> EnumerateDirectories(string parentDirectory, string searchPattern, SearchOption searchOpt)
{
try
{
var directories = Enumerable.Empty<string>();
if (searchOpt == SearchOption.AllDirectories)
{
directories = Directory.EnumerateDirectories(parentDirectory)
.SelectMany(x => EnumerateDirectories(x, searchPattern, searchOpt));
}
return directories.Concat(Directory.EnumerateDirectories(parentDirectory, searchPattern));
}
catch (UnauthorizedAccessException ex)
{
return Enumerable.Empty<string>();
}
}
public static IEnumerable<string> EnumerateFiles(string path, string searchPattern, SearchOption searchOpt)
{
try
{
var dirFiles = Enumerable.Empty<string>();
if (searchOpt == SearchOption.AllDirectories)
{
dirFiles = Directory.EnumerateDirectories(path)
.SelectMany(x => EnumerateFiles(x, searchPattern, searchOpt));
}
return dirFiles.Concat(Directory.EnumerateFiles(path, searchPattern));
}
catch (UnauthorizedAccessException ex)
{
return Enumerable.Empty<string>();
}
}
}
示例用法:
foreach(string fileName in SafeFileEnumerator.EnumerateFiles(folderPath, "*" + extension, SearchOption.AllDirectories))
{
//Do something with filename, store into an array or whatever you want to do.
}
这篇关于尝试从没有权限的位置添加文件时如何处理UnauthorizedAccessException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!