Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, I want to see if text typed into a textbox is contained in a text file.
So if I were to type "hello" in the textbox I would like to know if the text file has that word, Thanks.
Posted
Updated 12-May-12 22:26pm
v2

C#
public bool checkForText(string filePath, string textBoxText)
{       
   using (System.IO.StreamReader reader = new System.IO.StreamReader(filePath))
   {
       string[] linesToComapare = reader.ReadToEnd().Split('\n');
       for (int i = 0; i < linesToCompare.Count(); i++)
       {
          if (linesToCompare[i].Contains(textBoxText))
           {
               return true;
           }
       }
   }
      return false;
}
 
Share this answer
 
Comments
MR. AngelMendez 12-May-12 21:53pm    
thanks, both solutions are helpful. I will check into it.
VJ Reddy 12-May-12 22:43pm    
Good answer. 5!
charles henington 13-May-12 4:29am    
Thanks VJ :) Great example to you as well
Wendelius 13-May-12 3:31am    
Nice
charles henington 13-May-12 4:19am    
Thanks Mika :)
 
Share this answer
 
Comments
charles henington 12-May-12 22:10pm    
Great link on the read text file word by word using linq!!! My 5
Maciej Los 13-May-12 4:32am    
Thank you ;)
VJ Reddy 12-May-12 22:42pm    
Good references, particularly the last one. 5!
Maciej Los 13-May-12 4:32am    
Thank you ;)
Wendelius 13-May-12 2:57am    
Really good
The references given by losmac in Solution 2 are good.

In case if you want to only check whether a word typed in the TextBox is present in the text file then I think the Regex option is simple to use as shown below
C#
if (Regex.IsMatch(System.IO.File.ReadAllText(textFileName),
        string.Format(@"\s+{0}\s+",TextBox1.Text),
        RegexOptions.CultureInvariant | RegexOptions.IgnoreCase))
            MessageBox.Show("Found");

If you want to match case then remove | RegexOptions.IgnoreCase part in the above statement.
 
Share this answer
 
Comments
Wendelius 13-May-12 3:33am    
Very nice
VJ Reddy 13-May-12 3:50am    
Thank you, Mika :)
charles henington 13-May-12 4:20am    
Very nice VJ.. I haven't looked into regex much but it seems to be a very useful tool that would be worth looking into :)
VJ Reddy 13-May-12 4:30am    
Thank you, charles :)
Maciej Los 13-May-12 4:32am    
Great answer! +5

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