如何读取一个文件与CR / LF字符串保存? [英] How to read a file into a string with CR/LF preserved?

查看:1614
本文介绍了如何读取一个文件与CR / LF字符串保存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我问的问题是如何读取一个文件到一个字符串答案是显而易见的。然而 - 这里是抓与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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆