c# - OutOfMemoryException 文件内容

标签 c#

<分区>

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

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

最佳答案

您可以使用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;
        }
    }
}

关于c# - OutOfMemoryException 文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25245595/

相关文章:

c# - MVC - HTML 缩小是否值得?

c# - 如何为 Span<byte> 创建结构

c# - 通过.net使用java web服务-数据不一致

c# - 这是 async void 的正确用法吗? Xamarin

c# - 在 C# 中引用属性本身。反射?通用的?类型?

c# - Caliburn NotifyOfPropertyChanged : System. InvalidCastException

c# - 在 ASP.NET Core 2.x 中实现 EasyNetQ 发布/订阅模式的正确方法是什么?

c# - 如何使用 Spliton 和类型映射复杂对象?

c# - 如何将 IObservable<IObservable<T>> 转换为 IObservable<IEnumerable<T>>?

c# - 示例请求正文中 JsonPatchDocument 的 Swagger 意外 API PATCH 操作文档