简体   繁体   中英

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

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

In .NET 4 you could very efficiently do eg:

        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

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
    {

    }

}

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.

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 />");
}
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM