# \[C#\] Scan Directories

**URL:** <https://forum.kirupa.com/t/c-scan-directories/216024>\
**Category:** open source\
**Created:** [February 13, 2007, 2:29am UTC](https://forum.kirupa.com/t/c-scan-directories/216024 "2007-02-13T02:29:14Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [February 13, 2007, 2:29am UTC](https://forum.kirupa.com/t/c-scan-directories/216024/1 "2007-02-13T02:29:14Z")

</div>

I wrote a small Depth First Search program that recursively scans folders given a starting path:

```auto

[SIZE=2][/SIZE][SIZE=2][COLOR=#000000] public List<string> StartSearch(string path)
        {
            DirectoryInfo[] directoryListing = new DirectoryInfo(path).GetDirectories();[/COLOR][/SIZE]
[SIZE=2][COLOR=#000000] List<string> openList = new List<string>();
            List<string> closedList = new List<string>();
            List<string> folderNames = new List<string>();[/COLOR][/SIZE]
[SIZE=2][COLOR=#000000] openList.Add(path);[/COLOR][/SIZE]
[SIZE=2][COLOR=#000000] while (openList.Count != 0)
            {
                string currentPath = openList[0];
                openList.RemoveAt(0);[/COLOR][/SIZE]
[SIZE=2][COLOR=#000000] try
                {
                    DirectoryInfo[] neighbors = new DirectoryInfo(currentPath).GetDirectories();
                    for (int i = 0; i < neighbors.Length; i++)
                    {
                        DirectoryInfo currentFolder = neighbors*;
                        openList.Add(currentFolder.FullName);
                        folderNames.Add(currentFolder.Name);
                    }
                    closedList.Add(currentPath);
                }
                catch (UnauthorizedAccessException e)
                {
                    //Some folders will not be accessible
                }
            }
            return folderNames;
        }
    }[/COLOR][/SIZE]
[SIZE=2][COLOR=#000000] class Program
    {
        static void Main(string[] args)
        {
            FolderSearch foo = new FolderSearch();
            List<string> folderNames = foo.StartSearch("C:\\Program Files");[/COLOR][/SIZE]
[SIZE=2][COLOR=#000000] //foreach (string f in folderNames)
            //{
            // Console.WriteLine(f);
            //}
        }
    }[/COLOR][/SIZE]

```

You can modify this easily to access files instead of folders and/or to find a specific folder or file 😉

Cheers!  
Kirupa C:-)  
[SIZE=2]  
[/SIZE]
