c#如何向内存流添加换行符

时间:2016-03-08 14:48:22

标签: c# .net

例如,我正在合并3个文件,但最终文件之间没有换行符......

MemoryStream m = new MemoryStream();
File.OpenRead("c:\file1.txt").CopyTo(m);
File.OpenRead("c:\file2.txt").CopyTo(m);
File.OpenRead("c:\file3.txt").CopyTo(m);
m.Position = 0;
Console.WriteLine(new StreamReader(m).ReadToEnd());

如何在内存流中添加换行符?

3 个答案:

答案 0 :(得分:6)

您可以将换行符写入流中。你需要决定你想要哪一个。可能你需要Encoding.Xxx.GetBytes(Environment.NewLine)。您还需要决定使用哪种编码(必须与其他文件的编码匹配)。

由于换行符串是ASCII,重要的只是单字节编码和使用更多字符串编码的区别。例如,Unicode每个换行符使用两个字节。

如果您需要猜测,您可能应该使用没有BOM的UTF 8。

您还可以尝试基于全文的方法:

var result = File.ReadAllLines(a) + Environment.NewLine + File.ReadAllLines(b);

我还要指出,你需要处理你打开的流。

答案 1 :(得分:3)

又快又脏:

MemoryStream m = new MemoryStream();
File.OpenRead("c:\file1.txt").CopyTo(m);
m.WriteByte(0x0A);                // this is the ASCII code for \n line feed
                                  // You might want or need \n\r in which case you'd 
                                  // need to write 0x0D as well.
File.OpenRead("c:\file2.txt").CopyTo(m);
m.WriteByte(0x0A);
File.OpenRead("c:\file3.txt").CopyTo(m);
m.Position = 0;
Console.WriteLine(new StreamReader(m).ReadToEnd());

但正如@usr指出的那样,你真的应该考虑编码。

答案 2 :(得分:0)

假设您知道编码,例如UTF-8,则可以执行以下操作:

using (var ms = new MemoryStream())
{
    // Do stuff ...
    var newLineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
    ms.Write(newLineBytes, 0, newLineBytes.Length);
    // Do more stuff ... 
}