1

目标文件:

Hello
World

代码:

if (file != null)
{
    //Read file one character at a time
    StreamReader reader;
    reader = new StreamReader(file);
    do
    {
        int s = reader.Read();
        char sC = (char)s;
        if (sC.Equals(Environment.NewLine))
        {
            Console.WriteLine("+1");
        }
        Console.WriteLine((char)s);
    } while (!reader.EndOfStream);
    reader.Close();
    reader.Dispose();
}

输出:

H
e
l
l
o




W
o
r
l
d

因此(sC.Equals(Environment.NewLine)),一次读取一个字符时显然没有检测到与平台无关的换行符..我该怎么做?

4

5 回答 5

6

试试这个

if (sC.Equals('\n'))

如果您确定总会有一个\r,那么您可以用另一个电话\n吞下它。reader.Read();例子:

if (sC.Equals('\n')) {
   reader.Read()
   Console.WriteLine("+1");
}
于 2012-05-28T14:09:16.987 回答
2

这是因为Environment.NewLine它是String\r\n(取决于您的环境,在 Windows 平台上它是\r\n)组成的 - 它们是回车符和换行符 - 它是通常定义新行的一对。

所以比较一个字符(可以是\n\r\r\n总是会产生false

相反,正如@jurgen d 的回答中提到的,尝试比较\n.

于 2012-05-28T14:11:38.530 回答
0

Environment.NewLine实际上是两个字符:\r\n

你真的需要一次读一个字符吗?您不喜欢使用 aStringReader并使用 ReadLine() 吗?

于 2012-05-28T14:13:08.520 回答
0

删除的简单方法\n\r

        String text = "test\n\r";
        if (text[text.Length - 1] == 10 && text[text.Length - 2] == 13)
            text= text.Substring(0, text.Length - 2);
于 2013-11-08T15:34:28.663 回答
0

用这个-

if (sC.Equals('\r'))

在您的情况下,因为 '\r' 出现在 '\n' 之前。

于 2020-07-11T16:44:12.950 回答