Search File inside a folder using wild card

10,234

Solution 1

You can use the overload that takes the search pattern:

String fileNamePart = "a";
String fileExtension= ".jpg";
String searchPattern = String.Format("{0}*{1}", fileNamePart, fileExtension);
dirInfo.GetFiles(searchPattern)

If you want all in one query, you can also use LINQ:

lstFiles = dirInfo.EnumerateFiles(searchPattern)
                  .Select(file => new ATTFile(){
                      FileName = file.Name;
                      Folder = file.Directory.ToString();
                      Size = int.Parse(file.Length.ToString());
                      Extension = file.Extension;
                  }).ToList();

Note that i'm using DirectoryInfo.EnumerateFiles here since it can be more resource-efficient when you are working with many files and directories.

Solution 2

Use DirectoryInfo.GetFiles Method (String), you can specify wild card with it

* - Zero or more characters.

? - Exactly one character.

You can try:

dirInfo.GetFiles("a*");

instead of ? you may use * in your query to get files which starts with searchquery and ends with any other characters.

Share:
10,234
4b0
Author by

4b0

Updated on June 15, 2022

Comments

  • 4b0
    4b0 almost 2 years

    I try to search a file using wild card.My code is:

              string  SearchQuery ='';
               List<ATTFile> lstFiles = new List<ATTFile>();
                if (Directory.Exists(FilePath))
                {
                    DirectoryInfo dirInfo = new DirectoryInfo(FilePath);//File PAth is not a problem.
    
                  foreach (FileInfo file in dirInfo.GetFiles(SearchQuery + "?"))//Want help here  
                  {
    
                        ATTFile obj = new ATTFile();
                        obj.FileName = file.Name;
                        obj.Folder = file.Directory.ToString();
                        obj.Size = int.Parse(file.Length.ToString());
                        obj.Extension = file.Extension;
                        lstFiles.Add(obj);
    
                    }
    
    
                }
    

    Code Works if I give full file name. For Example: Inside a directory I have following files.

    and.jpg
    asp.jpg
    bb.jpg
    cc.jpg 
    

    Using above code if I give full file name its work means SearchQuery ="and.jpg".Its work.But If I give SearchQuery ="a" I want a result

    and.jpg
    asp.jpg
    

    Starts all files with a.Is it possible using wild card inside GetFiles(SearchQuery + "?").Thanks.