【发布时间】:2014-04-06 18:12:34
【问题描述】:
我在关注这个article
我想出了这个代码:
string FileName = "C:\\test.txt";
using (StreamReader sr = new StreamReader(FileName, Encoding.Default))
{
string[] stringSeparators = new string[] { "\r\n" };
string text = sr.ReadToEnd();
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
foreach (string s in lines)
{
Console.WriteLine(s);
}
}
这里是示例文本:
somet interesting text\n
some text that should be in the same line\r\n
some text should be in another line
这是输出:
somet interesting text\r\n
some text that should be in the same line\r\n
some text should be in another line\r\n
但我想要的是这样的:
somet interesting textsome text that should be in the same line\r\n
some text should be in another line\r\n
我想我应该得到这个结果,但不知何故我错过了一些东西......
【问题讨论】:
-
为什么不使用
File.ReadAllLines或File.ReadLines? -
Console.WriteLine()将在数组中的每个字符串之后自动添加换行符。您想在循环之前将这些行合并在一起,或者按照一个答案的建议,在Split文本之前替换\n。 -
我想要以
\r\n而不是\n或\r结尾的行。 -
问题不在于你最后有
\r\n和\n,而是你忘记了这些行实际上已经包含换行符。因此,即使您删除它们,文件中也只有三行。 -
你确定输出的第一行以
\r\n结尾吗?添加这一行,看看是否是你所期望的:Console.WriteLine("lines.Length={0}", lines.Length);