Sunday, 19 July 2015

Get word Count in a File using Regex in C#





By Regular Expression you can read the entire text file using the StreamReader class and then use the Regular Expression (Regex Class) to look for new line character using the Matches method. Regex should come up with a collection of the list of matches. Then you can get the count of the collection which will be the number of lines in the text file. Here is a code example of how you do it.
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
protected void Button1_Click(object sender, EventArgs e)
{
string FileName = string.Empty;

       FileName = Server.MapPath("ErrorLog\\Log.txt");

       Label1.Text = this.FileWordCount("Exception", FileName).ToString();
}

private int FileWordCount(string searchedWord, string filenameWithPath)
{
int RetVal = 0;           
       string FileText;

       try
       {
              using (StreamReader SR = new StreamReader(filenameWithPath))
              {
                    FileText = SR.ReadToEnd();
              }

              Regex RExp = new Regex(searchedWord, RegexOptions.Multiline);
              MatchCollection MatchedSearch = RExp.Matches(FileText);

              RetVal = MatchedSearch.Count;
}
       catch (Exception)
       {  
       }

       return RetVal;
}





No comments:

Post a Comment