Search This Blog

Monday, December 2, 2013

Search for files in directories and subdirectories C#

C# > Files > Search

GetDirectories: gets the names of subdirectories in a specified directory.
GetFiles: returns the names of files in a specified directory.

Example: Search for files in directories and subdirectories

          List<string> sfiles = new List<string>();
         FileDirSearch(@"C:\\", sfiles, "*.xml");

      void FileDirSearch(string sDir, List<string> sfiles, string pattern)
        {
            try
            {
                foreach (string d in Directory.GetDirectories(sDir))
                {
                    foreach (string f in Directory.GetFiles(d, pattern))
                    {
                        sfiles.Add(f);
                    }
                    FileDirSearch(d, sfiles, pattern);
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show (exc.Message);
            }
        }