【问题标题】:stringReader.ReadLine() cutting off end of filestringReader.ReadLine() 切断文件结尾
【发布时间】:2021-08-20 16:28:50
【问题描述】:

我正在使用 StringReader 读取 csv 文件。我注意到它没有完全阅读一些 csv,而其他人会完全阅读。文件的大小不是问题。我将问题缩小到使用

while(stringReader.Peek() >= 0){
    results += stringReader.ReadLine();
}

因为当我使用

results = stringReader.ReadToEnd();

我会得到整个文件。

使用第一种方法的一些变体对我来说很重要,因为这样更容易对文件中的每条记录执行我需要执行的操作。

作为说明,第一种方法直接取自微软文档 https://docs.microsoft.com/en-us/dotnet/api/system.io.streamreader.readline?view=net-5.0

【问题讨论】:

    标签: c# asp.net csv


    【解决方案1】:

    stringReader.Peak(),我假设您尝试输入 stringReader.Peek()

    无论如何,此方法返回下一个可用值而不消耗它。这不是一种可靠的方法来检测您何时到达文件末尾。

    如您所见,StreamReader.ReadLine() 在没有更多行可读取时返回null。这应该用于确定您何时到达终点。

    您可以将语法缩短为:

    string line;
    while ((line = stringReader.ReadLine()) != null)
    {
        // line contains the current line here
    }
    

    【讨论】:

    • 大声笑感谢您让我知道我的错字。是的,这有点干净
    【解决方案2】:

    不知何故,stringReader.Peek() >= 0 在读取文件的过程中返回 false。所以我对此的解决方案是修改while循环。这是我的最终工作解决方案。

    while(true)
    {
        result = stringReader.ReadLine();
        if(results == null || results == "")
            break;
        ...
    }
    

    【讨论】:

    • 你也可以使用string line; while((line=stringReader.ReadLine())!=null){/*do stuff with line*/}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    • 2013-04-13
    • 2014-11-30
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多