简体   繁体   English

如何在 C# 中使用 StreamReader 加载大文件?

[英]How to load large file with StreamReader in C#?

I'm using StreamReader in C# to load a txt file into a list it's work fine with small size file <= 20 Mb but when I need to load large files the prepossess stopped and show me this我在 C# 中使用 StreamReader 将 txt 文件加载到列表中,它适用于小文件 <= 20 Mb 但是当我需要加载大文件时,prepossess 停止并向我展示这个

Your app has entered a break state, but no code is currently executing that is supported by the selected debug engine (eg only native runtime code is executing).您的应用已进入中断 state,但当前没有执行所选调试引擎支持的代码(例如,仅执行本机运行时代码)。

I'm using Visual Studio 2017.我正在使用 Visual Studio 2017。

This is the code这是代码

line = reader.ReadLine();

while (line != null)
{
    if (line.Contains("@"))
    {
        myEmails.Add(line);
        line = reader.ReadLine();
    }
}
reader.Close();

Your code just has a minor logical error.您的代码只是有一个小的逻辑错误。

In your loop, you are looking for lines containing an @ symbol.在您的循环中,您正在寻找包含@符号的行。 If the line has one, it adds it to myEmails and gets the next line.如果该行有一个,它将它添加到myEmails并获取下一行。

However, if the line does not contain an @ , the next line is never read so you enter an infinite loop.但是,如果该行不包含@则永远不会读取下一行,因此您将进入无限循环。

You just need to move line = reader.ReadLine();你只需要移动line = reader.ReadLine(); outside of your if statement and it will always read the next line regardless of whether it contains an @ symbol:if语句之外,它总是会读取下一行,无论它是否包含@符号:

line = reader.ReadLine();
while (line != null)
{
    if (line.Contains("@"))
        myEmails.Add(line);

    line = reader.ReadLine();
}
reader.Close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM