Code Snippets

  

C# Source Code


Welcome to Dream.In.Code
Getting C# Help is Easy!

Join 95,475 C# Programmers for FREE!. Ask your question and get quick answers from Dream.In.Code experts. There are 956 online right now! We're the #1 programming help community on the internet! Registration is fast and FREE... Join Now!

Chat LIVE With a C# Expert

Register to Make This Box Go Away!



Search Text file for String

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

Submitted By: marcells23
Actions:
Rating:
Views: 5,405

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.


Add comment


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





Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month
-->