Click here to Skip to main content
Click here to Skip to main content

Tagged as

How to Get a List of Files and Folders Without Directory.GetFiles Access Denied Error

, 20 Jul 2009
Rate this:
Please Sign up or sign in to vote.
I know the title is a bit long, but it descriptive of the problem. Recently I had need to retrieve a listing of files and folders given a root path. All worked well, until I tested on Vista and Windows 7 machines. When trying to browse the "Users" folder, I kept getting access denied errors and no

I know the title is a bit long, but it descriptive of the problem. Recently I had need to retrieve a listing of files and folders given a root path. All worked well, until I tested on Vista and Windows 7 machines. When trying to browse the "Users" folder, I kept getting access denied errors and no lists returned. The problem is that Directory.GetFiles and Directory.GetDirectories will fail on the first sign of an access denied issue. On Vista and Windows 7, most of the directories under the Users folder are ACL'd to not allow reading or browsing.

The solution is to use a DirectoryInfo object to get the list of directories, and loop through those. The solution I present below uses PLINQ (Parallel LINQ) for multi-threaded looping. If you do not have PLINQ installed, simply change the Parallel.ForEach statements to the standard ForEach.

Notice the use of a Predicate in both functions. This allows you to add advanced filtering, for example only returning files with an extension of ".jpg", or only returning files modified in the last five days.

using System; 
using System.IO; 
using System.Threading; 
  
namespace MStaller 
{ 
    internal static class DirectoryListing 
    { 
        #region DirectoryList 
  
        /// <span class="code-SummaryComment"><summary> </span>
        /// Returns a list of directories under RootDirectory 
        /// <span class="code-SummaryComment"></summary> </span>
        /// <span class="code-SummaryComment"><param name="RootDirectory">starting directory</param> </span>
        /// <span class="code-SummaryComment"><param name="SearchAllDirectories">when true, all sub directories</span>
        ///             will be searched as well<span class="code-SummaryComment"></param> </span>
        /// <span class="code-SummaryComment"><param name="Filter">filter to be done on directory. use null for no</span>
        ///                      filtering<span class="code-SummaryComment"></param> </span>
        public static List<string> DirectoryList(string RootDirectory,
            bool SearchAllDirectories, Predicate<string> Filter) 
        { 
            List<string> retList = new List<string>(); 
  
            try 
            { 
                // create a directory info object 
                DirectoryInfo di = new DirectoryInfo(RootDirectory); 
  
                // loop through directories populating the list 
                Parallel.ForEach(di.GetDirectories(), folder => 
                { 
                    try 
                    { 
                        // add the folder if it passes the filter 
                        if ((Filter == null) || (Filter(folder.FullName))) 
                        { 
                            // add the folder 
                            retList.Add(folder.FullName); 
  
                            // get it's sub folders 
                            if (SearchAllDirectories) 
                                retList.AddRange(DirectoryList(folder.FullName, true,
                                    Filter)); 
                        } 
                    } 
 
                    catch (UnauthorizedAccessException) 
                    { 
                        // don't really need to do anything 
                        // user just doesn't have access 
                    } 
  
                    catch (Exception excep) 
                    { 
                        // TODO: log the exception 
                    } 
                }); 
            } 
  
            catch (Exception excep) 
            { 
                // TODO: save exception 
            } 
  
            // return the list 
            return retList; 
        } 
  
        // DirectoryList 
        #endregion 
  
        #region FileList 
  
        /// <span class="code-SummaryComment"><summary> </span>
        /// Returns a list of files under RootDirectory 
        /// <span class="code-SummaryComment"></summary> </span>
        /// <span class="code-SummaryComment"><param name="RootDirectory">starting directory</param> </span>
        /// <span class="code-SummaryComment"><param name="SearchAllDirectories">when true, all sub directories will</span>
        ///              be searched as well<span class="code-SummaryComment"></param> </span>
        /// <span class="code-SummaryComment"><param name="Filter">filter to be done on files/directory. use null for no</span>
        ///              filtering<span class="code-SummaryComment"></param> </span>
        public static List<string> FileList(string RootDirectory,
            bool SearchAllDirectories, Predicate<string> Filter) 
        { 
            List<string> retList = new List<string>(); 
  
            try 
            { 
                // get the list of directories 
                List<string> DirList = new List<string> { RootDirectory }; 
  
                // get sub directories if allowed 
                if (SearchAllDirectories) 
                    DirList.AddRange(DirectoryList(RootDirectory, true, null)); 
  
                // loop through directories populating the list 
                Parallel.ForEach(DirList, folder => 
                { 
                    // get a directory object 
                    DirectoryInfo di = new DirectoryInfo(folder); 
  
                    try 
                    { 
                        // loop through the files in this directory 
                        foreach (FileInfo file in di.GetFiles()) 
                        { 
                            try 
                            { 
                                // add the file if it passes the filter 
                                if ((Filter == null) || (Filter(file.FullName))) 
                                    retList.Add(file.FullName); 
                            } 
  
                            catch (Exception excep) 
                            { 
                                // TODO: log the exception 
                            } 
                        } 
                    } 
  
                    catch (UnauthorizedAccessException) 
                    { 
                        // don't really need to do anything 
                        // user just doesn't have access 
                    } 
  
                    catch (Exception excep) 
                    { 
                        // TODO: log the exception 
                    } 
                }); 
            } 
  
            catch (Exception excep) 
            { 
                // TODO: save exception 
            } 
  
            // return the list 
            return retList; 
        } 
  
        // FileList 
        #endregion 
    } 
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

merlin981
Software Developer (Senior)
United States United States
Winner - Best Mobile App - AT&T Developer Summit, Las Vegas, 2013
 
My personal resume can be found at: http://www.philippiercedeveloper.com
 
My game portfolio can be found at: http://www.rocketgamesmobile.com
 
About Philip Pierce:
 
I am a software developer with twenty years experience in game development, mobile, web, desktop, server, and database. My extensive background highlights an expertise in rapid application development using the latest Microsoft, Mobile, and Game Development technologies, along with the ability to create AI for games and business software, redesign existing software, develop multi-threaded software, and create client/server applications.

Comments and Discussions

 
Questioncreating the Predicate Pinmemberdave200712-Nov-12 15:25 
GeneralBug in Windows 7 CFileDialog while working with filtering list of files and folders. PinmemberANIL KUMAR SHARMA (INDIA)21-Oct-09 18:07 
There is a bug in Listview control of CFileDialog in windows 7 as it failed to work. For more details refer
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=489672&wa=wsignin1.0[^]
 
[AKS]

QuestionLink to PLINQ? PingroupSTLMike16-Oct-09 8:55 
AnswerRe: Link to PLINQ? Pinmembermerlin98116-Oct-09 12:23 
GeneralInteresting but why PLINQ Pinmemberkidzopa30-Jul-09 4:41 
GeneralRe: Interesting but why PLINQ Pinmembermerlin98130-Jul-09 4:59 
GeneralRe: Interesting but why PLINQ Pinmemberkidzopa30-Jul-09 5:02 
Generalretlist PinmemberJean-Paul Mikkers20-Jul-09 11:12 
GeneralRe: retlist Pinmembermerlin98120-Jul-09 11:18 
GeneralRe: retlist PinmemberMd. Marufuzzaman20-Jul-09 21:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140814.1 | Last Updated 20 Jul 2009
Article Copyright 2009 by merlin981
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid