views:

162

answers:

1

I'd like to know if there is a better alternative to my following code (preferably using LINQ)

            #region List and filter directories to only 3 levels deep
            // List all subdirectories within main directory
            string[] folders = Directory.GetDirectories(@"C:\pdftest\", "*" ,SearchOption.AllDirectories);
            List<string> subdirectories = new List<string>();

            //Filter away all main directories, now we are left with subdirectories 3 levels deep
            for (int i = 0; i<folders.Length; i++)
            {
                int occurences = folders[i].Split('\\').Length-1;
                if (occurences==4)
                    subdirectories.Add(folders[i]);             
            }
            #endregion
A: 

Untested, but something like this should do it.

        string[] subDirectories = Directory.GetDirectories(@"C:\pdftest\", "*", SearchOption.AllDirectories).Where(folder => folder.Split('\\').Length <= 4).ToArray();
Robin Day
The idea is not bad, but what happens if you start in folder C:\Program Files\Microsoft.NET\SDK\CompactFramework
Oliver
I was merely replicating the functionality that was in the original code.
Robin Day