Darren Young
Darren Young

Reputation: 11090

C# Recurse Directories using Directory.GetFiles and search pattern

I want to find all excel files within a directory structure using recursion. The problem is, the search pattern used in Directory.GetFiles only allows a single extension at a time.

Does anybody know a way around this or do I have to recurse through the directories multiple times looking for specific extensions? Or can you just grab every single file, and then loop through that list looking for specific extensions. Either way sounds a little inefficient.

Thanks

Upvotes: 3

Views: 7128

Answers (6)

areyesram
areyesram

Reputation: 169

I think the second alternative is more efficient. Loop through every file with the following pattern: .xl, then narrow the list looking for specific endings.

Something like:

foreach (String f in Directory.GetFiles(path, "*.xl*", SearchOption.AllDirectories))
{
    if (HasSomeExcelExtension(f))
        files .Add(f);
}

You could use the EndsWith method to check "f" against each extension, or extract the extension using the Path.GetExtension method and look it up in a hashtable containing the desired extensions.

just my $.02 hth

Upvotes: 0

sehe
sehe

Reputation: 392833

In .NET every version there is SearchOption.TopDirectoryOnly and SearchOption.AllDirectories

In .NET 4 you could very efficiently do e.g.:

        var regex = new Regex(@"\d+", RegexOptions.Compiled);

        var files = new DirectoryInfo(topdir)

            .EnumerateFiles("*.*", SearchOption.AllDirectories)

            .Where(fi => regex.IsMatch(fi.Name));

(This example filters for files having two digits in the name)

To emulate this, write a recursive enumerator method (yield return) to return all files, and filter the result like so:

 IEnumerable<FileInfo> Recurse(string topdir)
 { 
      // for each GetFiles() array element
      //      if is_not_dir yield return
      //      else Recurse(subdir)          
 }

 var filtered = Recurse.Where(fi => regex.IsMatch(fi.Name));

HTH

Upvotes: 6

safi
safi

Reputation: 3766

To loop through directory and sub directories, No Matter how much sub folder or files are, you can get the files into an array. You can specify the type file, Jpeg, Excel, Msword what ever you want in the extension section.

string [] Excel_Files;
String path = "what ever is your path";

Files=  Directory.GetFiles(Path, "*.XL", SearchOption.AllDirectories).Select(x => Path.GetFileName(x)).ToArray();

or To specify Multiple search option for different file extensions you can do like this:

public string[] getFiles(string SourceFolder, string Filter, 
 System.IO.SearchOption searchOption)
{

ArrayList alFiles = new ArrayList();

 string[] MultipleFilters = Filter.Split('|');

 foreach (string FileFilter in MultipleFilters)
 {
       alFiles.AddRange(Directory.GetFiles(SourceFolder, FileFilter, searchOption));
 }

 return (string[])alFiles.ToArray(typeof(string));
}

public void button_click()
{

string[] sFiles = getFiles(Server.MapPath("~/"), 
 "*.gif|*.jpg|*.png|*.bmp|*.XL|*.PNG", 
 SearchOption.AllDirectories);

foreach (string FileName in sFiles)
{
 Response.Write(FileName + "<br />");
}
}

Upvotes: 0

Florian Greinacher
Florian Greinacher

Reputation: 14786

If you only want to get all excel files, use the pattern ".xl".

Otherwise I would suggest to call Directory.GetFiles without pattern and filter the matching extensions by hand.

Upvotes: 0

Emond
Emond

Reputation: 50672

In .NET 4 there is an extra overload that allows the inclusion of subfolders

EDIT oops I did not read the question very well...

Have a look here

Upvotes: 0

BugFinder
BugFinder

Reputation: 17858

Modify your recursive loop and have a list of patterns. eg

static private void walk(String name)
{
    try
    {
        foreach (String pattern in Patterns)
        {
            foreach (String f in Directory.GetFiles(name, pattern))
            {
                Console.WriteLine(f);
             } 
        }
            foreach (String d in Directory.GetDirectories(name))
        {
            walk(d);
        }
    }
    catch
    {

    }

}

Upvotes: 0

Related Questions