C# School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

 

Code Snippets

  

C# Source Code


Welcome to Dream.In.Code
Become a C# Expert!

Join 300,308 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 2,102 people online right now. Registration is fast and FREE... Join Now!





Search Text file for String

Searches a text file for a string by using Regex.IsMatch

Submitted By: marcells23
Actions:
Rating:
Views: 25,446

Language: C#

Last Modified: September 19, 2007
Instructions: input the path to the text file and the string to search for.

Snippet


  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Text.RegularExpressions;
  5. using System.IO;
  6.  
  7. namespace searchTxtFile
  8. {
  9.     class searchTxt
  10.     {
  11.         static void Main()
  12.         {
  13.             string fName = @" ";//path to text file
  14.             StreamReader testTxt = new StreamReader(fName);
  15.             string allRead = testTxt.ReadToEnd();//Reads the whole text file to the end
  16.             testTxt.Close(); //Closes the text file after it is fully read.
  17.             string regMatch = " ";//string to search for inside of text file. It is case sensitive.
  18.             if (Regex.IsMatch(allRead,regMatch))//If the match is found in allRead
  19.             {
  20.                 Console.WriteLine("found\n");
  21.  
  22.             }
  23.             else
  24.             {
  25.                 Console.WriteLine("not found\n");
  26.             }
  27.  
  28.         }
  29.     }
  30. }
  31.  

Copy & Paste


Comments


demo123 2008-01-30 03:06:00

Buggy snippet, without object dispose and etc., not optimal written

d10x1d3 2008-06-18 01:48:27

Thanks, This helped a lot.

wartech 2008-08-26 23:28:21

Thanks this was a big help!

bsit-ia barkada 2008-10-03 07:28:13

we want a code that is for file system like library system and service record system.

lordelf2004 2008-11-24 13:19:50

Can I count the occurrence of a string in text file?

carck3r 2009-03-29 07:46:28

Thanks! That was so helpful.

chreddy4u@gmail.com 2009-06-26 06:10:06

How to search if I have string like this Request.QueryString("id")


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C# Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month