0

I am trying to write a simple code that writes all the folders in a drive to the console.

To skip the folders with unauthorized access, I have used a try catch block. Some programmers do not accept this as elegant coding.

Is there a better way to do this.

Here is what I have written.

static void Main(string[] args)
    {
        Queue<DirectoryInfo> directories = new Queue<DirectoryInfo>();

        DirectoryInfo dr = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);

        directories.Enqueue(dr.Root);
        DirectoryInfo[] subdr = null;

        while (directories.Count > 0)
        {
            dr = directories.Dequeue();

            Console.WriteLine(dr.ToString());

            try
            {
                subdr = dr.GetDirectories();

                foreach (DirectoryInfo directory in subdr)
                {
                    if (directory.Exists)
                        directories.Enqueue(directory);
                }
            }
            catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); }
        }
    }
  • 2
    *"Some programmers do not accept this as elegant coding."* - so what do those programmers suggest you do instead? – UnholySheep Sep 18 '17 at 14:23
  • The best approach IMHO is to not filter the directories to begin with. Why? Windows doesn't do it, why should you? Apart from the fact that authorizations can change and the information you show can therefore be stale, what's wrong with simply informing the user that he has no access to a given directory only when he tries to access it? – InBetween Sep 18 '17 at 14:30

0 Answers0