如何ReadLine并保留回车和换行?

时间:2012-06-15 11:59:19

标签: c# readline

当读取流上的一行时(对我而言,它实际上是COM端口上的流),返回的字符串不包含\ n或\ r \ n字符(或\ r \ n组合)。出于记录目的,我想保留它们。目前我的循环看起来像这样:

 while (newPort.BytesToRead > 0)
 {
     received = ReadLine(newPort);

     response.Add(received);
 }

所以基本上我正在读取一个字符串,然后将其添加到名为response的字符串列表中。我想要的是返回的字符串received包含原始流中的\ r或\ n或\ r \ n,以及终止一行文本。

这是否有可能?甚至是非平凡的!

我猜这很难做到。我的意思是考虑它,如果我收到\ r,我必须得到下一个字符,看看它是否是\ n。如果没有下一个字符,我将超时并发生异常。如果有下一个字符并且它不是\ n,我必须在下一次迭代时使其成为当前字符,依此类推......!

3 个答案:

答案 0 :(得分:1)

添加Environment.NewLine后,您可以附加received

更新如果您需要逐字保留原始空白,那么使用ReadLine就没有意义了。在这种情况下,您可以使用ReadBlock来读取文件的较小块,或ReadToEnd来获取整个文件。如果您需要标记新行来处理消息,您可以搜索原始字符串以进行规范化或标记化或者您想要做的任何事情。

答案 1 :(得分:1)

这是来自问题帖子的OP解决方案:

  

好的,我对它有所了解。这是我认为正确的......:

            {
                int s = 0, e = 0;

                for (; e < line.Length; e++)
                {
                    if (line[e] == '\n')
                    {
                        // \n always terminates a line.

                        lines.Add(line.Substring(s, (e - s) + 1));

                        s = e + 1;
                    }
                    if (line[e] == '\r' && (e < line.Length - 1))
                    {
                        // \r only terminates a line if it isn't followed by \n.

                        if (line[e + 1] != '\n')
                        {
                            lines.Add(line.Substring(s, (e - s) + 1));

                            s = e + 1;
                        }
                    }
                }

                // Check for trailing characters not terminated by anything.

                if (s < e)
                {
                    lines.Add(line.Substring(s, (e - s)));
                }
            }

答案 2 :(得分:-1)

while (newPort.BytesToRead > 0)
 {
     received = ReadLine(newPort);

     response.Add(string.Format("{0}{1}", received, System.Environment.Newline);
 }