【问题标题】:OutOfMemoryException contents of files [duplicate]OutOfMemoryException 文件内容[重复]
【发布时间】:2014-08-11 22:25:23
【问题描述】:

我有以下代码将文件的内容加载到内存中,但我想要一个更好的方法,因为我收到了以下错误

 Unhandled Exception: OutOfMemoryException.

有没有更有效的方法来处理我要查看的大多数文件都是 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);
                }
            }
        }
    }
}

【问题讨论】:

  • 您是否尝试过一次读取一行文件并在找到您要查找的字符串时停止?

标签: c#


【解决方案1】:

您可以使用StreamReader.ReadLine逐行处理文件。

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;
        }
    }
}

【讨论】:

  • 感谢完美的工作
猜你喜欢
  • 1970-01-01
  • 2013-01-19
  • 2020-12-10
  • 1970-01-01
  • 2018-07-30
  • 2016-10-09
  • 2014-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多