Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 951
derp_in_mouth Avatar asked Dec 21 '22 16:12

derp_in_mouth


2 Answers

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);
like image 70
Sergey Vyacheslavovich Brunov Avatar answered Dec 29 '22 11:12

Sergey Vyacheslavovich Brunov


Try

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

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

like image 29
heljem Avatar answered Dec 29 '22 12:12

heljem