我想列出程序可以访问的所有文件和文件夹,并将它们写入文本文件。我将如何获得清单?我需要一种方法来捕获或不抛出UnauthorizedAccessExceptions在不可访问的文件夹上。

最佳答案

请尝试使用以下代码:

private static IEnumerable<string> Traverse(string rootDirectory)
{
    IEnumerable<string> files = Enumerable.Empty<string>();
    IEnumerable<string> directories = Enumerable.Empty<string>();
    try
    {
        // The test for UnauthorizedAccessException.
        var permission = new FileIOPermission(FileIOPermissionAccess.PathDiscovery, rootDirectory);
        permission.Demand();

        files = Directory.GetFiles(rootDirectory);
        directories = Directory.GetDirectories(rootDirectory);
    }
    catch
    {
        // Ignore folder (access denied).
        rootDirectory = null;
    }

    if (rootDirectory != null)
        yield return rootDirectory;

    foreach (var file in files)
    {
        yield return file;
    }

    // Recursive call for SelectMany.
    var subdirectoryItems = directories.SelectMany(Traverse);
    foreach (var result in subdirectoryItems)
    {
        yield return result;
    }
}


客户代码:

var paths = Traverse(@"Directory path");
File.WriteAllLines(@"File path for the list", paths);

07-26 00:04