Search File inside a folder using wild card

Shree picture Shree · Sep 28, 2012 · Viewed 10.2k times · Source

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.

Answer

Habib picture Habib · Sep 28, 2012

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.