c# - How to list all files and folders on a hard drive?

余生颓废 提交于 2019-12-05 02:43:32

问题


I want to list all files and folders that my program has access to and write them to a text file. How would I get the list? I need a way that will catch or not throw UnauthorizedAccessExceptions on folders that are not accessible.


回答1:


Please try using the code:

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;
    }
}

Client code:

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



回答2:


Try

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

This should give you a array containing all files on the hard disk.




回答3:


Check out Directory.GetFiles() and related methods.




回答4:


You can try with

var files = from file in Directory.EnumerateFiles(@"your Path", "*.*", SearchOption.AllDirectories)
            select file;



回答5:


Using Traverse that Serge suggested and the DriveInfo class you can have access to all files available to the pc.

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);
   }
}


来源:https://stackoverflow.com/questions/12332703/c-sharp-how-to-list-all-files-and-folders-on-a-hard-drive

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!