简体   繁体   中英

Get access to windows folders in C#

I am making a software with Winforms and C# 7.0. I have to get all the files in C:\\Program Files and C:\\Program Files (x86) . When I try Directory.GetFiles(@"C:\\Program Files\\", "*.*", SearchOption.AllDirectories I get an exception that the access to the path C:\\Program Files\\Common Files' is denied.

I tried to start my program as an administrator but it still doesn't work. How can I get a list of all files in access-denied folders and read them?

Kind regards

You will have to skip the directories you can't read (assuming that you can't run your program under the System account or other account with privileges to read all directories).

You have to be careful here because you can't use yield inside a try/catch . Here's one approach:

public static IEnumerable<string> EnumFilesRecursively(string rootDirectory)
{
    // Helper method to call GetEnumerator(), returning null on exception.

    IEnumerator<T> getEnumerator<T>(Func<IEnumerable<T>> getEnumerable)
    {
        try   { return getEnumerable().GetEnumerator(); }
        catch { return null; }
    }

    // Enumerate all files in the current root directory.

    using (var enumerator = getEnumerator(() => Directory.EnumerateFiles(rootDirectory)))
    {
        if (enumerator != null)
            while (enumerator.MoveNext())
                yield return enumerator.Current;
    }

    // Recursively enumerate all subdirectories.

    using (var enumerator = getEnumerator(() => Directory.EnumerateDirectories(rootDirectory)))
    {
        if (enumerator != null)
            while (enumerator.MoveNext())
                foreach (var file in EnumFilesRecursively(enumerator.Current))
                    yield return file;
    }
}

To test it:

public static void Main(string[] args)
{
    foreach (var file in EnumFilesRecursively(@"C:\Program Files\"))
    {
        Console.WriteLine(file);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM