4

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

4

5 回答 5

9

请尝试使用以下代码:

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);
于 2012-09-08T17:07:49.870 回答
2

尝试

string[] files = Directory.GetFiles(@"C:\\", "*.*", SearchOption.AllDirectories);

这应该为您提供一个包含硬盘上所有文件的数组。

于 2014-04-03T15:49:19.633 回答
0

检查Directory.GetFiles()和相关方法。

于 2012-09-08T16:59:15.597 回答
0

你可以试试

var files = from file in Directory.EnumerateFiles(@"your Path", "*.*", SearchOption.AllDirectories)
            select file;
于 2012-09-08T16:59:53.070 回答
0

使用 Serge 建议的 Traverse 和 DriveInfo 类,您可以访问电脑可用的所有文件。

DriveInfo[] allDrives = DriveInfo.GetDrives();

foreach (DriveInfo d in allDrives)
{
   if (d.IsReady == true)
   {
      var paths = Traverse(d.Name);
      File.AppendAllLines(@"File path for the list", paths);
   }
}
于 2012-09-08T17:34:34.633 回答