c# - int.TryParse 在 StreamReader 的第一行数据上返回 false

标签 c#

老读者,第一次海报。

我只是使用 StreamReader 类将文本文件中的数字读入一个整数数组,每行一个整数。我通读了一次文件以获取行数,以便我可以正确定义目标数组。然后我将指针重置为文本文件的开头并再次读取,这次使用 int.TryParse 将字符串转换为整数并写入数组。但是文件的第一行从 TryParse 返回“false”——即使字符串只是“3”。后续行返回“true”就好了。这是片段......

        _NumbersInMemory = new int[lineCount];

        theFileStream.DiscardBufferedData();
        theFileStream.BaseStream.Seek(0, 0);

        lineCount = 0;
        do
        {
            string theLineFromTheFle = theFileStream.ReadLine();
            int numberInMemoryTemporarily = 0;
            bool result = int.TryParse(theLineFromTheFle, out numberInMemoryTemporarily);
            if (result)
            {
                _NumbersInMemory[lineCount] = numberInMemoryTemporarily;
            }
            lineCount++;
        } while (!theFileStream.EndOfStream);

        theStream.Close();

重置到文件开头(只有 82 行)是否会弄乱 TryParse 第一次迭代的输入,或者类似的东西?

最佳答案

我会考虑改用这段代码:

_NumbersInMemory =
    File
        .ReadAllLines(@"path")
        .Select(line => line.Trim())
        .Select(line =>
        {
            int numberInMemoryTemporarily = 0;
            if (int.TryParse(line, out numberInMemoryTemporarily))
            {
                return numberInMemoryTemporarily;
            }
            return 0;
        })
        .ToArray();

.Select(line => line.Trim()) 可能足以解决您遇到的问题。

关于c# - int.TryParse 在 StreamReader 的第一行数据上返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35168355/

相关文章:

c# - 将 FTP 服务器上现有的文件附加到 C# .NET 中的邮件

c# - 尝试在 Unity 中自动运行单元测试

c# - 使用 XPath 从 XML 文件中提取 XML 元素

c# - 在表单上设计面板

c# - 将 OpenId Connect 与 Azure AD 结合使用,然后模拟现有的身份用户

c# - 在 ASP.Net c# 中执行多个读取器

c# - 在另一个应用程序中处理按钮单击

c# - 我可以使用 JavascriptSerializer 反序列化为不可变对象(immutable对象)吗?

c# - 如何正确发出和使用类?

c# - LINQ:透明的记录插入和更新