Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# int.TryParse在StreamReader的第一行数据上返回false_C# - Fatal编程技术网

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

C# int.TryParse在StreamReader的第一行数据上返回false,c#,C#,长期读者,第一次海报 我只是使用StreamReader类将数字从文本文件读入整数数组,每行一个整数。我将该文件通读一次,以获得行数,以便正确定义目标数组。然后我重置指向文本文件开头的指针并再次读取,这次使用int.TryParse将字符串转换为整数并写入数组。但是文件的第一行从TryParse返回'false',即使字符串仅仅是'3'。后面的行返回“true”很好。这是片段 _NumbersInMemory = new int[lineCount]; theF

长期读者,第一次海报


我只是使用
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行),将输入输入到TyPARSE的第一次迭代,或类似的事情?

< P>我会考虑使用此代码代替:

_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())
可能足以解决您的问题。

您的文件的开头可能有UTF8或Unicode字节顺序标记(BOM)。在十六进制查看器中查看文件可以验证这一点

第一次打开文件时,
StreamReader
类读取这些字节,以确定文件其余部分的正确编码。第一个
ReadLine()
将不包括这些字节

通过查找底层流的字节0,下一个
ReadLine()
将包含这些字节,因为
StreamReader
不知道应该跳过它们(它已经读取并处理了这些字节)


使用
ReadAllLines
读取文件一次,或者关闭并重新打开文件以重新开始读取,而不是返回到开头。

是否可能在
3
后面有空格?“即使字符串仅为“3”。。。是“3”还是“3”?为什么不改用File.ReadAllLines。。?另外,首先尝试修剪字符串,这与您的问题没有太大关系,但是:我假设,您当前的代码依赖于这样一个事实,即文件中至少有一行(do-while循环)。为了挑剔起见,要查找的第二个参数应该是SeekOrigin.Begin,而不是零。使用有意义的常量可以使代码更具可读性。