Program running as admin can't access some paths

1.5k views Asked by At

I'm creating a C# program which check signatures for all .exe files and do some other checks. The application request to run as admin with UAC, and checks it at start (We are sure is running with admin privileges).

However, when I check recursively some paths, I got folders where I don't have access. For example:

DirectoryInfo dir = new DirectoryInfo(System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData));
FileInfo[] files = dir.GetFiles("*.exe", SearchOption.AllDirectories);

is throwing:

 System.UnauthorizedAccessException: Access to the path 'C:\ProgramData\Application Data' is denied.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileSystemEnumerableIterator`1.AddSearchableDirsToStack(SearchData localSearchData)
   at System.IO.FileSystemEnumerableIterator`1.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.IO.DirectoryInfo.InternalGetFiles(String searchPattern, SearchOption searchOption)
   at "the lines above"

Is there any way to access those paths? In case it's not possible, a way to GetFiles skips those paths without stopping is also very appreciated.

2

There are 2 answers

4
Christoph Fink On BEST ANSWER

Just because you are an admin does not mean you can access everything!
E.g. a users personal folder is also not accessible for an admin "by default", but as an admin you can "give yourself that right".

So either you change the rights on all such folders or just leave out such folders.

UPDATE:

In case it's not possible, a way to GetFiles skips those paths without stopping is also very appreciated.

You could choose a recursive scan "per folder" (should be done anyhow IMO):

public void Scan(DirectoryInfo dir = null)
{
    if (dir == null)
    {
        dir = new DirectoryInfo(System.Environment
              .GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData));
    }

    try
    {
        var dirs = dir.GetDirectories();
        foreach (var subDir in dirs)
            Scan(subDir);

        var files = dir.GetFiles("*.exe", SearchOption.TopDirectoryOnly);
        foreach (var file in files)
            // check file
    }
    catch(UnauthorizedAccessException)
    {
        // log error
    }
}
0
Kamakazi On

Have you tried adding read/write permissions on the files you are attempting to access via command prompt?

If you are only requiring access to this file temporary, it is best to remove the permissions after you are done with the reading/writing, otherwise, I would look into giving certain users permissions instead of modifying permissions in your file system. Either way works, depending on your goal.

http://support.microsoft.com/kb/308419