尝试从没有权限的位置添加文件时如何处理UnauthorizedAccessException

时间:2012-12-19 14:35:00

标签: c#

我试图以这种方式从文件夹中获取所有文件:

try
{
    string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
}
catch (UnauthorizedAccessException)
{
    throw;
}

如果我的根文件夹包含用户无权访问的文件夹,则会捕获UnauthorizedAccessException并且我的数组为空并且所有递归都失败。

我如何处理此案例并确保我的代码在未经许可的情况下忽略位置但是从具有权限的位置添加文件?

1 个答案:

答案 0 :(得分:3)

您可以使用FileSystemInfo对象和递归来完成此任务:

static List<string> files = new List<string>();

static void MyMethod() {
    DirectoryInfo dir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
    ProcessFolder(dir.GetFileSystemInfos());
}

static void ProcessFolder(IEnumerable<FileSystemInfo> fsi) {
    foreach (FileSystemInfo info in fsi) {

        // We skip reparse points 
        if ((info.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint) {
            Debug.WriteLine("Skipping reparse point '{0}'", info.FullName);
            return;
        }

        if ((info.Attributes & FileAttributes.Directory) == FileAttributes.Directory) {
            // If our FileSystemInfo object is a directory, we call this method again on the
            // new directory.
            try {
                DirectoryInfo dirInfo = (DirectoryInfo)info;
                ProcessFolder(dirInfo.GetFileSystemInfos());
            }
            catch (Exception ex) {
                // Skipping any errors
                // Really, we should catch each type of Exception - 
                // this will catch -any- exception that occurs, 
                // which may not be the behavior we want.
                Debug.WriteLine("{0}", ex.Message);
                break;
            }
        } else {
            // If our FileSystemInfo object isn't a directory, we cast it as a FileInfo object, 
            // make sure it's not null, and add it to the list.
            var file = info as FileInfo;
            if (file != null) {
                files.Add(file.FullName);
            }
        }
    }
}

MyMethod获取您选择的路径并使用它创建DirectoryInfo对象,然后调用GetFileSystemInfos()方法并将其传递给ProcessFolder方法。

ProcessFolder方法查看每个FileSystemInfo对象,跳过reparse points,如果FileSystemInfo对象是目录,则再次调用ProcessFolder方法 - 否则,它将FileSystemInfo对象强制转换为FileInfo对象,确保它不为空,然后将文件名添加到列表中。

更多阅读: