static void Main(string[] args)
{
Console.WriteLine("Enter the file path: ");
var filePath = Console.ReadLine();
Console.WriteLine("Enter text to search: ");
var searchTerm = Console.ReadLine();
var fsLib = new FSLibrary();
Console.WriteLine("No. of matches: {0}", fsLib.SearchOccurances(filePath, searchTerm));
Console.ReadKey();
}
public int SearchOccurances(string filePath, string searchTerm)
{
int occurances = 0;
var fileContents = File.ReadAllText(filePath);
if (!String.IsNullOrEmpty(fileContents))
{
MatchCollection matches = Regex.Matches(fileContents, searchTerm, RegexOptions.IgnoreCase);
if (matches != null)
{
occurances = matches.Count;
}
}
return (occurances);
}Simple code snippet which makes use of Regular expression function to search number of occurrences of a string in a text file.