Alan Alan - 1 month ago 10
C# Question

GetFiles Access Denied Exception

I am trying to recursively go through a directory and use GetFiles to return a list of all the files in that directory. Here is my code so far:

public string[] passFiles(string location)
{
string[] files;
try
{
files = Directory.GetFiles(location);
return files;
}
catch (UnauthorizedAccessException)
{
// Code here will be hit if access is denied.
throw;
}
}


But it still gives me an Access Denied error. When I try to leave the catch part blank, it says that all paths must return something, so that's why I put the
throw
statement. Any ideas as to why this isn't ignoring the error and going on to the next one?

Answer

When an exception occurs and you catch the exception, you still need to return a result for the function. Initialize your variable files to contain an empty array and then return it after the try-catch-block, so it is always returned, even when an error occurs.

public string[] passFiles(string location)
{
    // Create an empty array that will be returned in case something goes wrong
    string[] files = new string[0];
    try
    {
        files = Directory.GetFiles(location);
    }
    catch (UnauthorizedAccessException)
    {
        // Code here will be hit if access is denied.
    }

    return files;
}

See also this question for a similar question and some useful answers.