A more elegant way to read and write all accessible folders in a drive

34 views Asked by At

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); }
        }
    }
0

There are 0 answers