Thursday, November 1, 2012

C# FileSearch & Parse

I was in need of a simple recursive key word search in a file structure. This console app helped me search for a key word in CiscoReports .srd files.


using

System;
using

System.Collections.Generic;
using

System.Linq;
using

System.Text;
using

System.IO;
namespace

FileSearch
{

class Program
{


static void Main(string[] args)
{

GetList();
}

public static void GetList()
{

string dir = @"c:\ciscoreports\";


string[] filePaths = Directory.GetFiles(dir, "*.*",

SearchOption.AllDirectories);

foreach (string value in filePaths)
{
ReadFile(value);
}

Console.Read();
}

public static void ReadFile(string fileName)
{

int counter = 0;

string line;

string searchString = "historical";


// Read the file and display it line by line.
System.IO.
StreamReader file = new System.IO.StreamReader(fileName);

while ((line = file.ReadLine()) != null)
{

if (line.Contains(searchString))
{

Console.WriteLine("Report Name:" + fileName);

Console.WriteLine(counter.ToString() + ": " + line);

Console.WriteLine("");

// Console.Read();
}
counter++;
}
file.Close();
}
}
}

0 comments:

Post a Comment