Pages

Wednesday, April 22, 2009

Find text in mutiple files

School coming soon but I don't want to touch my resume or anything to get ready for the school :(. To make things worse, my employer is bit busy these days and he is not giving any work for my this/next week. Wasted all day doing nothing or improving class website UI. And now that I was finally able to get my self down to touching the resume, I found writing out a finder irresistible!

Finds text in the all files in the given directory:

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

public class Finder
{
public static FindObject[] FindText(string directory_path, string text)
{
string [] files = Directory.GetFiles(directory_path);

List findObjList = new List();

try
{
foreach (string fName in files)
{
StreamReader testTxt = new StreamReader(fName);
string allRead = testTxt.ReadToEnd();//Reads the whole text file to the end
testTxt.Close(); //Closes the text file after it is fully read.
string regMatch = text;//string to search for inside of text file. It is case sensitive.

if (Regex.IsMatch(allRead, regMatch))//If the match is found in allRead
{
FindObject findObj = new FindObject();
findObj.success = true;
findObj.filename = fName;
findObjList.Add(findObj);
}
}
}
catch (Exception err)
{
Console.Out.WriteLine(err.Message);
}

return findObjList.ToArray();
}
}

public class FindObject
{
public string filename;
public bool success;
}

No comments:

Post a Comment