Search if text is present in a file

Hi, in this article I will show you how to find whether a text is present in a file or not ,and how to use them in the code,you can use the below code snippet to accomplish the task, It needs System.IO StramReader to read the file and Contains() to check the string

1. Create a class and method to find the text in a file :
The Class named Searcher has IsFoundInFile Method ,which plays the role of searching string in a file. IsFoundInFile is kept 'static' as doesn't need object to initiate

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace SEARCH
public static class Searcher
public static bool IsFoundInFile(string str, string path)
bool stringFound= false;
string currentline;
using (StreamReader file = new StreamReader(path))
while ((currentline = file.ReadLine()) != null)
if (currentline.Contains(str))
stringFound = true;
return stringFound;

2. Use the method to find if text is present or not, in your program:
reference the namespace SEARCH Searhcer.IsFoundInFile to do the function.

if (SEARCH.Searcher.IsFoundInFile(strSearchString,file))
Console.WriteLine("The text is present in the file");


No responses found. Be the first to comment...

  • Name: