user2825489
user2825489

Reputation: 11

Method Directory.GetDirectories failures

Very odd that I am experiencing a occasional errors when calling the GetDirectories() method.

This started happening when our IT dept remotely moved some folders to my local machine. This error only occurs when navigating through these folders using C#.

Error Message: 'Access to the path 'C:\Users\XXXX\XXXXX is denied'

Code:

public static string[] GetDirectoryInfo(string path)
{
    if (Directory.Exists(path))
    {
        //This call is failing on the new folder.
        return Directory.GetDirectories(path);
    }
    return new string[0];
}

Not very complicated, correct?

Navigating with Windows Explorer, the folder isn't present.

In the CMD prompt I can change directory to this folder; following up with the DIR command I get the error 'File not found'.

I am guessing the problem is a Win32 issue and something didn't get cleaned up when the folder was moved. I have no idea how to correct the issue, except for digging through decompiled System.IO classes; which I will do if I don't get a solution.

Upvotes: 1

Views: 976

Answers (2)

Karl Anderson
Karl Anderson

Reputation: 34846

Your code is probably trying to access hidden folders that are not accessible to your account/role.

The easiest solution is to catch the UnauthorizedAccessException and just eat it, so it essentially skips the directory, like this:

public static string[] GetDirectoryInfo(string path)
{
    if (Directory.Exists(path))
    {
        try 
        { 
            //This call is failing on the new folder.
            return Directory.GetDirectories(path);
        }
        catch(UnauthorizedAccessException unAuthEx)
        {
            // Do nothing to eat exception
        }
    }
    return new string[0];
}

Upvotes: 3

Transcendent
Transcendent

Reputation: 5755

This occurs when the software tries to access folders which have been restricted by the windows for security reasons like for example :

C:\Users\Default  (This path is not accessible by your code)

Another reason would be that your application is trying to access folders which are not really folders like

My Music
My Pictures

If you are trying to read all the folders in a specific drive, then you can make some exception to handle these directories, another thing that MIGHT help you is to run your application as administrator.

Upvotes: 0

Related Questions