Counting a Phrase in a Text File


This function helps to count number of occurences of a phrase in a text file, it will take 2 parameters file name and phrase to search

Function


public int CountPhraseInFile(string strFileName, string strFindText)
{
int retValue = 0;
StreamReader sr;
try
{
sr = File.OpenText(strFileName);
string strText = sr.ReadToEnd();
string strReplace = strText.Replace(strFindText, "");
int count = (strText.Length - strReplace.Length) / strFindText.Length;
retValue = count;
sr.Close();
sr.Dispose();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
return retValue;
}


To Test the function


Response.Write(CountPhraseInFile(@"C:\downloads\test.txt", "type").ToString());


Comments

Author: PHANI HARSHITHA MADALA03 Feb 2010 Member Level: Gold   Points : 1

Hi Mr.satish,

Very usefull info..

Thanks for sharing with all of us.


regards,

harshitha

Author: Satish Kumar J03 Feb 2010 Member Level: Gold   Points : 0

Thank you Harshitha.



  • 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:
    Email: