1

I have the following code which loads the contents of the file to memory but I want a better way as I am getting the following error

 Unhandled Exception: OutOfMemoryException.

Is there a more efficient way of handling this most files I am going to be looking through are 1.85 GB

 class Program
{

    public static string sDate;
    public static string sTerm;
    static void Main(string[] args)
    {
        Console.WriteLine("Enter the date to search - yyyy-mm-dd");
        sDate = Console.ReadLine();
        Console.WriteLine("Enter search term");
        sTerm = Console.ReadLine();
        DirectoryInfo di = new DirectoryInfo(Environment.GetEnvironmentVariable("ININ_TRACE_ROOT") + "\\" + sDate + "\\");
        FileInfo[] files = di.GetFiles("*.ininlog");
        foreach (FileInfo file in files)
        {
            using (StreamReader sr = new StreamReader(file.FullName))
            {
                string content = sr.ReadToEnd();
                if (content.Contains(sTerm))
                {
                    Console.WriteLine("{0} contains\"{1}\"", file.Name, sTerm);
                }
            }
        }
    }
}
ondrovic
  • 1,105
  • 2
  • 23
  • 40
  • Have you tried reading the files one line at a time and stopping if the string you are looking for is found? – D Stanley Aug 11 '14 at 14:25

1 Answers1

4

You can use StreamReader.ReadLine to process the file line-by-line.

using (StreamReader sr = new StreamReader(file.FullName))
{
    string line;
    while((line = sr.ReadLine()) != null)
    { 
        if (line.Contains(sTerm))
        {
            Console.WriteLine("{0} contains\"{1}\"", file.Name, sTerm);
            break;
        }
    }
}
Chris Hinton
  • 866
  • 5
  • 15