Search code examples
c#asp.netfilefileinfo

Search File inside a folder using wild card


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.


Solution

  • 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.