Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to the path is denied when using Directory.GetFiles(...) [duplicate]

Tags:

c#

I'm running the code below and getting exception below. Am I forced to put this function in try catch or is there other way to get all directories recursively? I could write my own recursive function to get files and directory. But I wonder if there is a better way.

// get all files in folder and sub-folders
var d = Directory.GetFiles(@"C:\", "*", SearchOption.AllDirectories);

// get all sub-directories
var dirs = Directory.GetDirectories(@"C:\", "*", SearchOption.AllDirectories);

"Access to the path 'C:\Documents and Settings\' is denied."

like image 473
Amir Rezaei Avatar asked Feb 13 '11 19:02

Amir Rezaei


2 Answers

If you want to continue with the next folder after a fail, then yea; you'll have to do it yourself. I would recommend a Stack<T> (depth first) or Queue<T> (bredth first) rather than recursion, and an iterator block (yield return); then you avoid both stack-overflow and memory usage issues.

Example:

    public static IEnumerable<string> GetFiles(string root, string searchPattern)
    {
        Stack<string> pending = new Stack<string>();
        pending.Push(root);
        while (pending.Count != 0)
        {
            var path = pending.Pop();
            string[] next = null;
            try
            {
                next = Directory.GetFiles(path, searchPattern);                    
            }
            catch { }
            if(next != null && next.Length != 0)
                foreach (var file in next) yield return file;
            try
            {
                next = Directory.GetDirectories(path);
                foreach (var subdir in next) pending.Push(subdir);
            }
            catch { }
        }
    }
like image 65
Marc Gravell Avatar answered Sep 19 '22 10:09

Marc Gravell


You can set the program so you can only run as administrator.

In Visual Studio:

Right click on the Project -> Properties -> Security -> Enable ClickOnce Security Settings

After you clicked it, a file will be created under the Project's properties folder called app.manifest once this is created, you can uncheck the Enable ClickOnce Security Settings option

Open that file and change this line :

<requestedExecutionLevel level="asInvoker" uiAccess="false" />

to:

 <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />

This will make the program require administrator privileges, and it will guarantee you have access to that folder.

like image 40
Yochai Timmer Avatar answered Sep 19 '22 10:09

Yochai Timmer