Search File in a Directory

Following fucntion will take 2 arguments FileName to Search and Directory Name where to search, it will search all file those names starts with File Name passed

Explained the code inline

public List<string> SearchDirectory(string FileName, string DirectoryName)
//Declare a List of Strings for Returning File Names
List<string> strFileNames = new List<string>();
//Get the Directory Info using Directory Name
DirectoryInfo dirInfor = new DirectoryInfo(DirectoryName);
// Get all files whose names starts with FileName Passed
FileInfo[] filesInfo = dirInfor.GetFiles(FileName +
"*", SearchOption.TopDirectoryOnly);
//Loop through all the files found and add to
//List and return them
foreach (FileInfo fi in filesInfo)
catch (Exception ex)

return strFileNames;

Testing the above function

private void button1_Click(object sender, EventArgs e)
//Open the folder Browser Dialog for Selecting the directory
// and search text from a Text box
//Shows the no of files found the directory
+ " Files found");

Hope this helps.

SatishKumar J
Microsoft MVP(ASP.NET)



No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: