2

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.

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.