C# 如何在将字节数组写入文件时添加新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12950652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to add New Line while writing byte array to file
提问by Tim
Hi I am reading a audio file into a byte array. then i want to read every 4 bytes of data from that byte array and write it into another file.
嗨,我正在将音频文件读入字节数组。然后我想从该字节数组中读取每 4 个字节的数据并将其写入另一个文件。
I am able to do this but, my problem is i want to add new line aft every 4 byte of data is written to file. how to do that?? Here is my code...
我能够做到这一点,但是,我的问题是我想在每 4 个字节的数据写入文件后添加新行。怎么做??这是我的代码...
FileStream f = new FileStream(@"c:\temp\MyTest.acc");
for (i = 0; i < f.Length; i += 4)
{
byte[] b = new byte[4];
int bytesRead = f.Read(b, 0, b.Length);
if (bytesRead < 4)
{
byte[] b2 = new byte[bytesRead];
Array.Copy(b, b2, bytesRead);
arrays.Add(b2);
}
else if (bytesRead > 0)
arrays.Add(b);
fs.Write(b, 0, b.Length);
}
Any suggestions please.
请提出任何建议。
采纳答案by Nikola Davidovic
I think this might be the answer to your question:
我想这可能是你问题的答案:
byte[] newline = Encoding.ASCII.GetBytes(Environment.NewLine);
fs.Write(newline, 0, newline.Length);
So your code should be something llike this:
所以你的代码应该是这样的:
FileStream f = new FileStream("G:\text.txt",FileMode.Open);
for (int i = 0; i < f.Length; i += 4)
{
byte[] b = new byte[4];
int bytesRead = f.Read(b, 0, b.Length);
if (bytesRead < 4)
{
byte[] b2 = new byte[bytesRead];
Array.Copy(b, b2, bytesRead);
arrays.Add(b2);
}
else if (bytesRead > 0)
arrays.Add(b);
fs.Write(b, 0, b.Length);
byte[] newline = Encoding.ASCII.GetBytes(Environment.NewLine);
fs.Write(newline, 0, newline.Length);
}
回答by Boomer
Pass System.Environment.NewLineto the filestream
传递System.Environment.NewLine到文件流
For more info http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx
有关更多信息http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx

