none
Getting over the dreaded "Access Denied" error with Directory.GetFiles

    Question

  • Hi,

    I've been researching this topic quite a bit and cannot find an answer.

    I am writing a utility where one of its function is to scan for certain file types. Naturally, I use the Directory.GetFiles function. I have code to ignore folders and/or files I don't have access to. So that isn't the issue. My issue is, I want to access those files.

    The utility runs as a C# console application. I've included a custom manifest file that requires Administrator privileges to run. When I test this on my machine, my function won't even access Doc Settings/My Local Admin User/My Documents & My Pictures...etc.How is this possible?! If I am an Administrator on this machine, running a console app with administrator privileges, why can't I even access this folder? I even logged in as the main Administrator account and still can't get access.

    I am running on Windows 7. Developing in VS 2010. .NET Framework 4.0.

    The question: How do I gain access to the folders/files that give me an UnauthorizedAccessException? I know there is a way around this.

    Many many thanks for helping me solve this.


    Thursday, September 15, 2011 9:02 PM

Answers

All replies

  • It's probably not running elevated.
    Thursday, September 15, 2011 9:22 PM
  • I added a custom manifest to the project and have it embedded. I know it runs as Administrator because when I run it from my the command window it asks for consent to run as Administrator. Is that what you mean?

    If not, how do I run it elevated?

    Thursday, September 15, 2011 9:36 PM
  • If you get a UAC prompt it's run elevated.

    If you open PowerShell and navigate to the directory you're having problems with does [IO.Directory]::GetFiles() failes for the same reason.

    Thursday, September 15, 2011 10:06 PM
  • I ran it on a few of the directories I was having problems with. Still can't get to any of them. Access Denied.
    Thursday, September 15, 2011 10:55 PM
  • You may be running into "folder redirection", which is denying some users access to certain folders. Ever heard of it?

    http://msdn.microsoft.com/en-us/library/aa384187(v=VS.85).aspx

    http://msdn.microsoft.com/en-us/library/dd765197%28VS.85%29.aspx

    Rudy =8^D


    Mark the best replies as answers. "Fooling computers since 1971."

    http://thesharpercoder.blogspot.com/

    Thursday, September 15, 2011 11:34 PM
  • Thanks for the reply Rudy, but I don't think that's the problem.

    I'm just trying to do a search for certain file types. These are places I can get to normally under any and all other circumstances except when I run from my console application and use the Directory.GetFiles

    Friday, September 16, 2011 5:09 AM
  • If it helps, here is the very straight forward code:

    try
    {
        foreach (String file in Directory.GetFiles(directoryName, pattern, SearchOption.TopDirectoryOnly))
       {
           // do stuff
        }<br/>}<br/> catch (UnauthorizedAccessException uae)
    {
               //handle
    }
    catch (Exception e) 
    { 
               //handle
    }
    


    And here is my output:

    Access to the path 'C:\Documents and Settings\' is denied.
    Access to the path 'C:\ProgramData\Application Data\' is denied.
    Access to the path 'C:\ProgramData\Desktop\' is denied.
    Access to the path 'C:\ProgramData\Documents\' is denied.
    Access to the path 'C:\ProgramData\Favorites\' is denied.
    Access to the path 'C:\ProgramData\Start Menu\' is denied.
    Access to the path 'C:\ProgramData\Templates\' is denied.
    Access to the path 'C:\System Volume Information\' is denied.
    Access to the path 'C:\Users\AdminUser\AppData\Local\Application Data\' is denied.
    Access to the path 'C:\Users\AdminUser\AppData\Local\History\' is denied.
    Access to the path 'C:\Users\AdminUser\AppData\Local\Temporary Internet Files\' is denied.
    Access to the path 'C:\Users\AdminUser\Application Data\' is denied.
    Access to the path 'C:\Users\AdminUser\Cookies\' is denied.
    Access to the path 'C:\Users\AdminUser\Documents\My Music\' is denied.
    Access to the path 'C:\Users\AdminUser\Documents\My Pictures\' is denied.
    Access to the path 'C:\Users\AdminUser\Documents\My Videos\' is denied.
    Access to the path 'C:\Users\AdminUser\Local Settings\' is denied.
    Access to the path 'C:\Users\AdminUser\My Documents\' is denied.
    Access to the path 'C:\Users\AdminUser\NetHood\' is denied.
    Access to the path 'C:\Users\AdminUser\PrintHood\' is denied.
    Access to the path 'C:\Users\AdminUser\Recent\' is denied.
    Access to the path 'C:\Users\AdminUser\SendTo\' is denied.
    Access to the path 'C:\Users\AdminUser\Start Menu\' is denied.
    Access to the path 'C:\Users\AdminUser\Templates\' is denied.
    Access to the path 'C:\Users\All Users\Application Data\' is denied.
    Access to the path 'C:\Users\All Users\Desktop\' is denied.
    Access to the path 'C:\Users\All Users\Documents\' is denied.
    Access to the path 'C:\Users\All Users\Favorites\' is denied.
    Access to the path 'C:\Users\All Users\Start Menu\' is denied.
    Access to the path 'C:\Users\All Users\Templates\' is denied.
    Access to the path 'C:\Users\Default\AppData\Local\Application Data\' is denied.
    Access to the path 'C:\Users\Default\AppData\Local\History\' is denied.
    Access to the path 'C:\Users\Default\AppData\Local\Temporary Internet Files\' is denied.
    Access to the path 'C:\Users\Default\Application Data\' is denied.
    Access to the path 'C:\Users\Default\Cookies\' is denied.
    Access to the path 'C:\Users\Default\Documents\My Music\' is denied.
    Access to the path 'C:\Users\Default\Documents\My Pictures\' is denied.
    Access to the path 'C:\Users\Default\Documents\My Videos\' is denied.
    Access to the path 'C:\Users\Default\Local Settings\' is denied.
    Access to the path 'C:\Users\Default\My Documents\' is denied.
    Access to the path 'C:\Users\Default\NetHood\' is denied.
    Access to the path 'C:\Users\Default\PrintHood\' is denied.
    Access to the path 'C:\Users\Default\Recent\' is denied.
    Access to the path 'C:\Users\Default\SendTo\' is denied.
    Access to the path 'C:\Users\Default\Start Menu\' is denied.
    Access to the path 'C:\Users\Default\Templates\' is denied.
    Access to the path 'C:\Users\Default User\' is denied.
    Access to the path 'C:\Users\My Other User\AppData\Local\Application Data\' is denied.
    Access to the path 'C:\Users\My Other User\AppData\Local\History\' is denied.
    Access to the path 'C:\Users\My Other User\AppData\Local\Temporary Internet Files\' is denied.
    Access to the path 'C:\Users\My Other User\Application Data\' is denied.
    Access to the path 'C:\Users\My Other User\Cookies\' is denied.
    Access to the path 'C:\Users\My Other User\Documents\My Music\' is denied.
    Access to the path 'C:\Users\My Other User\Documents\My Pictures\' is denied.
    Access to the path 'C:\Users\My Other User\Documents\My Videos\' is denied.
    Access to the path 'C:\Users\My Other User\Local Settings\' is denied.
    Access to the path 'C:\Users\My Other User\My Documents\' is denied.
    Access to the path 'C:\Users\My Other User\NetHood\' is denied.
    Access to the path 'C:\Users\My Other User\PrintHood\' is denied.
    Access to the path 'C:\Users\My Other User\Recent\' is denied.
    Access to the path 'C:\Users\My Other User\SendTo\' is denied.
    Access to the path 'C:\Users\My Other User\Start Menu\' is denied.
    Access to the path 'C:\Users\My Other User\Templates\' is denied.
    Access to the path 'C:\Users\Public\Documents\My Music\' is denied.
    Access to the path 'C:\Users\Public\Documents\My Pictures\' is denied.
    Access to the path 'C:\Users\Public\Documents\My Videos\' is denied.
    Access to the path 'C:\Windows\CSC\v2.0.6\' is denied.
    Access to the path 'C:\Windows\System32\LogFiles\WMI\RtBackup\' is denied.

    I absolutely must be able to read all of that.

    Friday, September 16, 2011 2:54 PM
  • what Rudedog said
    Friday, September 16, 2011 2:58 PM
  • Yes, but I'm running on a 32-bit machine. According to Rudy's articles, this occurs in a 64-bit. So I don't see how and/or why that is the problem.
    Friday, September 16, 2011 3:32 PM
  • I just looked at the links.  I have not programmed for it but in Windows 7 when you click on a folders in "users" some of them say "access denied" even if you are an administrator.
    Friday, September 16, 2011 3:37 PM
  • What's the value you're using for directoryName? And what's the value for pattern? I see you're specifying TopDirectoryOnly and yet the output is showing child directories.
    • Proposed as answer by Jeff032 Friday, September 16, 2011 4:29 PM
    • Unproposed as answer by Jeff032 Friday, September 16, 2011 4:29 PM
    Friday, September 16, 2011 3:44 PM
  • For starters, the following paths for every user are not actual directories, and therefore there is no need for you to access them (if that is even possible)

     

    \Documents\My Music\

    \Documents\My Pictures\

    \Documents\My Videos\

    \My Documents\

     

     

    The actual directories for the above are

    \My Music\

    \My Pictures\

    \My Videos\

    \Documents\

     

    This most likely applies to some of the other directories you have listed.

     

    Also, note that while explorer shows the documents folder as "My Documents", if you click in explorer's address bar to change the path, it shows that it actually is called "Documents".


    • Edited by Jeff032 Friday, September 16, 2011 4:33 PM
    Friday, September 16, 2011 4:33 PM
  • What's the value you're using for directoryName? And what's the value for pattern? I see you're specifying TopDirectoryOnly and yet the output is showing child directories.

    I am starting at C:\ that is directory name. The code I put is inside an iterative function. So I eventually make it down the whole Directory tree. Pattern can be anything. Right now, I'm targeting *.pf and *svch*.* . I can get to all the other directories just fine.
    Friday, September 16, 2011 7:10 PM
  • For starters, the following paths for every user are not actual directories, and therefore there is no need for you to access them (if that is even possible)

     

    \Documents\My Music\

    \Documents\My Pictures\

    \Documents\My Videos\

    \My Documents\

     

     

    The actual directories for the above are

    \My Music\

    \My Pictures\

    \My Videos\

    \Documents\

     

    This most likely applies to some of the other directories you have listed.

     

    Also, note that while explorer shows the documents folder as "My Documents", if you click in explorer's address bar to change the path, it shows that it actually is called "Documents".



    Cool. How can I get to them programmatically? What about the other paths? Also, if those aren't the actual paths, then wouldn't I get a different exception - PathDoesNotExist(?) vs. UnauthorizedAccessException ?

    I am inside an iterative function. I will generally start my search at C:\ and make it all the way down. So when I get to these directories, how do I know? I use Directory.GetDirectories(directoryName) to get the child directories.

    Thanks guys!


    Friday, September 16, 2011 7:13 PM
  • For completeness sake.

     

    /// <summary>
            /// Recursive Search
            /// </summary>
            /// <param name="directoryName"></param>
            private void Search(String directoryName)
            {
                Boolean canAccess = true;   // if we break initially trying to read the directory, don't try to search its subdirectories later
    
                // iterate through all patterns
                foreach (String pattern in this._searchPatterns)
                {
                    try
                    {
                        
                        foreach (String file in Directory.GetFiles(directoryName, pattern, SearchOption.TopDirectoryOnly))
                        {
                           // do something
                        }
                    }
                    catch (UnauthorizedAccessException uae)
                    {
    // handle
                        canAccess = false;
                    }
                    catch (Exception e) 
                    { 
    // handle
                    }
                }
    
                if (canAccess)
                {
                    try
                    {
                        // iterate through subdirectories
                        foreach (String dir in Directory.GetDirectories(directoryName))
                        {
                            if (!dir.Equals(directoryName)) { this.Search(dir); }
                        }
                    }
                    catch (Exception e) { //handle }
                }
            }
    


    Friday, September 16, 2011 7:18 PM
  • You probably are going to those directories (C:\users\Public\Documents), you're just not getting an error for them. Most of those directories you're listing look like directories from Win XP, not Win 7.

    It is odd that you're getting an accessed denied instead of a DirectoryNotFound.

    Friday, September 16, 2011 7:22 PM
  • You may be running into "folder redirection", which is denying some users access to certain folders. Ever heard of it?

    http://msdn.microsoft.com/en-us/library/aa384187(v=VS.85).aspx

    http://msdn.microsoft.com/en-us/library/dd765197%28VS.85%29.aspx

     

    Thanks for the reply Rudy, but I don't think that's the problem.

    Don't thinks so, huh.

     

    I just looked at the links. I have not programmed for it but in Windows 7 when you click on a folders in "users" some of them say "access denied" even if you are an administrator.

     

    That's a good observation! It happens on 32-bit or 64-bit Windows 7. It can happen on Vista, too.

     

    It is odd that you're getting an accessed denied instead of a DirectoryNotFound.

     

    Good question.  If the path name were bad, I don't think you would get "Access Denied" either. 

    Rudy


    Mark the best replies as answers. "Fooling computers since 1971."

    http://thesharpercoder.blogspot.com/


    Friday, September 16, 2011 7:44 PM
  • You probably are going to those directories (C:\users\Public\Documents), you're just not getting an error for them. Most of those directories you're listing look like directories from Win XP, not Win 7.

    It is odd that you're getting an accessed denied instead of a DirectoryNotFound.


    So should I be using a different method to get sub directories? Or is there a function that finds the correct path mapping?
    Friday, September 16, 2011 7:45 PM
  • Doing a little poking around I see that those directories have the Hidden and ReparsePoint attributes. According to http://msdn.microsoft.com/en-us/library/aa365503(VS.85).aspx "Reparse points can be established for a directory, but the directory must be empty." So you could probably ignore directories which are ReparsePoints.

    Friday, September 16, 2011 7:53 PM
  • Doing a little poking around I see that those directories have the Hidden and ReparsePoint attributes. According to http://msdn.microsoft.com/en-us/library/aa365503(VS.85).aspx "Reparse points can be established for a directory, but the directory must be empty." So you could probably ignore directories which are ReparsePoints.


    Understood. But I know for a fact that a bunch of those directories on my local machine are not empty. Good to know though.
    Friday, September 16, 2011 7:56 PM
  • The link on Redirection was not the best one.  Sorry, I wasn't paying attention.  My bad.

    User Account Control Data Redirection.

    Data Redirection - Managed 

    Exercise 1: Exploring User Account Control Virtualization

    I think these will be of more help to you.

    Rudy  =8^D

     


    Mark the best replies as answers. "Fooling computers since 1971."

    http://thesharpercoder.blogspot.com/

    • Marked as answer by Khaled Dajani Friday, September 16, 2011 8:48 PM
    Friday, September 16, 2011 7:58 PM
  • If you go to the parent directories (say for example %userprofile%) in cmd and executed the dir command, is "My Documents" listed? I doubt it. "Documents" is there by default but "My Documents" is not. The list of directories you listed out earlier as being the ones that cause problems are directories which are actually just redirections to other directories. So your program is going to find the real directory, meaning you can safely ignore the empty Reparse point ones.
    • Marked as answer by Khaled Dajani Friday, September 16, 2011 8:48 PM
    Friday, September 16, 2011 8:05 PM
  • * FACE PALM *

    I completely understand now. Guys...Thank you so much!

    So basically, when I do Directory.GetDirectories() I am getting all my directories plus the Reparse points. So really, I am getting everything I need already.

    I just ran my tool and added a print to see what directory are getting hit. I should have just done this from the beginning. Man...I apologize for missing the point right away.

    Well now, I am still running my utility as a console app and requiring admin. So I get the UAC prompt. Can I programmatic-ally accept that prompt? I don't want the user to see it.

    Friday, September 16, 2011 8:48 PM
  • Also...I'm not sure who to mark as answer here, you guys were all correct. Shall I just mark all of you?
    Friday, September 16, 2011 8:48 PM
  • The user has to change their user settings to not prompt UAC. If programs could specify that every virus and piece of malware would specify no UAC.

    It's okay to mark both RudeDog and I.

    Friday, September 16, 2011 9:08 PM
  • Indeed.

    Well thanks very much fellas!

    Friday, September 16, 2011 9:16 PM
  • Thank you all for your active participation in the MSDN forum!

    Hi Khaled,
    Welcome to the MSDN forum!

    If you have any difficulty in future programming, you are welcome to post here again.

    Have a nice day!


    Yoyo Jiang[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, September 20, 2011 9:09 AM
  • I still have this problem... Perhaps a post of some working code might clear up some of the ambiguity.  (Instead of a thousand people all throwing out a bunch of suggestions, and they i try each one of them and finally idea number 998 works)... and let me be the first to say that this is a terrible issue and I just wrote my own getDirectories method and my own getFiles method to get around it... which leaves me with like thirty or forty lines of code as opposed to one...

    I am running Visual Studio 2010 as an administrator, and I am getting a System.UnauthorizedAccess error (what higher privilege do i need?!?).... ( Access to the path 'C:\Users\John.Bartels\Documents\My Videos' is denied.)... That directory does not even exist (be it from explorer, cmd, or powershell that I view the directory structure).

    Can someone please post a few Working lines of Code that circumvent this error and adequately explain the issue.  I know that the "AllDirectories" search option includes reparse points like mounted drives and symbolic links.  So... why wouldn't I have access to a symbolic link directory when I am running as administrator... Still makes no sense.  Please Post Code.

    Thanks,

    string [] files =

    System.IO.Directory.GetDirectories(@"C:\Users\John\Documents\", "*.txt", System.IO.SearchOption.AllDirectories);

    running on Windows 7 x64 with Visual Studio 2010

    I would like to Specify "AllDirectories" as my search option (because I don't want to my own recursive methods... why not?... because if the AllDirectories search option is there and i *Should be able to search a directory tree in one line of code... then that's what I would like to do.

    //should have just went to stackoverflow for my answer in the first place... simple explanation

    http://stackoverflow.com/questions/9089876/windows-service-running-as-system-cannot-access-c-users

    • Edited by John Bart Tuesday, October 30, 2012 7:46 PM
    Tuesday, October 30, 2012 7:39 PM
  • I am getting a System.UnauthorizedAccess error (what higher privilege do i need?!?).... ( Access to the path 'C:\Users\John.Bartels\Documents\My Videos' is denied.)... That directory does not even exist (be it from explorer, cmd, or powershell that I view the directory structure).

    The problem may not be privileges.  The issue could be that error code 5 became a catch all error code at some point (http://blogs.msdn.com/b/oldnewthing/archive/2005/01/17/354399.aspx), so there may be another issue that's not related to permissions.

    I agree with you that it's dumb that this fails. SearchOption.AllDirectories, should handle the Hidden + ReparsePoint issue, instead of hitting this.

    This might also make for an interesting read http://msdn.microsoft.com/en-us/library/bb513869.aspx.

    • Edited by jader3rd Tuesday, October 30, 2012 11:40 PM Added link.
    • Edited by Dummy yoyoModerator Wednesday, October 31, 2012 3:20 AM Modify the hyperlink.
    Tuesday, October 30, 2012 11:38 PM
  • I have read the article that you posted (http://msdn.microsoft.com/en-us/library/bb513869.aspx.) ... which is mostly what I ended up using.  However, I believe there should be a boolean flag to specify whether or not you want to include the Reparse Points.

    Otherwise, the call to GetDirectories with the SearchOption set to AllDirectories... will almost certainly fail... so why would I ever want to use it???... seems like there should be a boolean flag here that can leave out the Reparse Points... maybe then this Method Call would actually have some utility.

    • Edited by John Bart Wednesday, October 31, 2012 5:54 PM clarification
    Wednesday, October 31, 2012 5:52 PM