Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
How can I find exact/match string in textfile in c#?
Posted
Comments
Ed Nutting 30-May-12 4:52am    
Homework or laziness? Look up in Google "c# read text from file" then look at the IndexOf function.
Ed

you can read file and match the string in the data of .txt file
here is simple example

C#
private int GetLinesNoFromFile(string FileNameWithPath,string searchString)
        {
            string[] bt = null;
            if (System.IO.File.Exists(FileNameWithPath))
            {
                bt = System.IO.File.ReadAllLines(FileNameWithPath);
            }

            for (int i = 0; i < bt.Length; i++)
            {
                string str = bt[i].ToString();
                if (str.Contains(searchString))
                    return i; // data found in line no
            }
            return -1; // nodata found
        }
 
Share this answer
 
Comments
Prasad_Kulkarni 14-Jun-12 3:39am    
5'ed!
There are so many ways to achieve this. All start with reading the file in. Once you've read the file in, you could use one of the many string methods to identify the text, or you could use a regular expression. The appropriate technique really depends on what you are going to do with this information afterwards (e.g. if you need the position of the match, then a regular expression isn't the best choice).
 
Share this answer
 
Comments
Pandvi 30-May-12 4:59am    
Good guidance! +5!
Mohsen try this


private Boolean FindMyString(string thisFileName, string lookingFor, out int foundIt, out string errorMsg)
{
string entry=string.Empty ;
int fileIndex;

foundIt = 0;
errorMsg = string.Empty;
if (string.IsNullOrEmpty(thisFileName))
{
errorMsg = "No File passed on.";
return false;
}
if (!File.Exists(thisFileName))
{
errorMsg = "File name " + thisFileName + " does not exist?";
return false;
}
TextReader myTR = new StreamReader(thisFileName);
fileIndex = 0;
while ((entry = myTR.ReadLine()) != null)
{
if (entry.ToUpper().Trim().Contains(lookingFor))
{
foundIt = fileIndex+1;
myTR.Close();
return true;
}
}
errorMsg = lookingFor + " was not found in " + thisFileName + ".";
myTR.Close();
return false;

}


Example in your main function:


int foundIt=0;
string errorMsg=string.Empty;
string lookingFor="My FRIEND";
string thisFileName="c:\\Test.txt";


if (FindMyString(thisFileName, lookingFor, out foundIt, out errorMsg) == false)
Console.WriteLine("Your " + lookingFor + " was not found.");
else
Console.WriteLine("Your " + lookingFor + " was found at the point " + foundIt + ".");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900