如何读取一个文件与CR / LF字符串保存? [英] How to read a file into a string with CR/LF preserved?
问题描述
如果我问的问题是如何读取一个文件到一个字符串答案是显而易见的。然而 - 这里是抓与CR / LF保存
If I asked the question "how to read a file into a string" the answer would be obvious. However -- here is the catch with CR/LF preserved.
现在的问题是, File.ReadAllText
去掉这些字符。 StreamReader.ReadToEnd
只是转换成LF CR对我来说这导致了长期的调查在那里我有臭虫很明显的代码; - )
The problem is, File.ReadAllText
strips those characters. StreamReader.ReadToEnd
just converted LF into CR for me which led to long investigation where I have bug in pretty obvious code ;-)
因此,简而言之,如果我有一个包含文件 foo\\\
我想获得
\r\\\
bar foo\\ \
(即内容完全一致),而不是
\r\\\
bar 富栏
, foobar的
或 foo\\\
。有一些现成的净空间使用的方式?
\\\
\\\
bar
So, in short, if I have file containing foo\n\r\nbar
I would like to get foo\n\r\nbar
(i.e. exactly the same content), not foo bar
, foobar
, or foo\n\n\nbar
. Is there some ready to use way in .Net space?
的的结果应该总是一个字符串,包含整个文件。的
推荐答案
您确定这些方法是被剥离出你的人物的元凶?
Are you sure that those methods are the culprits that are stripping out your characters?
我试着写了一个快速测试; StreamReader.ReadToEnd
保留所有的换行符。
I tried to write up a quick test; StreamReader.ReadToEnd
preserves all newline characters.
string str = "foo\n\r\nbar";
using (Stream ms = new MemoryStream(Encoding.ASCII.GetBytes(str)))
using (StreamReader sr = new StreamReader(ms, Encoding.UTF8))
{
string str2 = sr.ReadToEnd();
Console.WriteLine(string.Join(",", str2.Select(c => ((int)c))));
}
// Output: 102,111,111,10,13,10,98,97,114
// f o o \n \r \n b a r
写入和从临时文件读出时的相同的结果实现的:
An identical result is achieved when writing to and reading from a temporary file:
string str = "foo\n\r\nbar";
string temp = Path.GetTempFileName();
File.WriteAllText(temp, str);
string str2 = File.ReadAllText(temp);
Console.WriteLine(string.Join(",", str2.Select(c => ((int)c))));
看来你换行符得到其他地方丢失了。
It appears that your newlines are getting lost elsewhere.
这篇关于如何读取一个文件与CR / LF字符串保存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!