【发布时间】:2011-11-07 09:44:03
【问题描述】:
用于写入文件字符串和字节[] 数组的流类是什么? 如果文件不存在,则需要打开文件以追加或创建新文件。
using (Stream s = new Stream("application.log")
{
s.Write("message")
s.Write(new byte[] { 1, 2, 3, 4, 5 });
}
【问题讨论】:
用于写入文件字符串和字节[] 数组的流类是什么? 如果文件不存在,则需要打开文件以追加或创建新文件。
using (Stream s = new Stream("application.log")
{
s.Write("message")
s.Write(new byte[] { 1, 2, 3, 4, 5 });
}
【问题讨论】:
使用BinaryWriter-Class
using (Stream s = new Stream("application.log")
{
using(var b = new BinaryWriter(s))
{
b.Write(new byte[] { 1, 2, 3, 4, 5 });
}
}
或者正如 Tim Schmelter 建议的(谢谢)只是 FileStream:
using (var s = new FileStream("application.log", FileMode.Append, FileAccess.Write)
{
var bytes = new byte[] { 1, 2, 3, 4, 5 };
s.Write(bytes, 0, bytes.Length);
}
如果需要,这个会附加或创建文件,但 BinaryWriter 更好用。
【讨论】:
尝试使用 BinaryWriter? http://msdn.microsoft.com/en-us/library/system.io.binarywriter.aspx
【讨论】:
也许您的情况需要更简单的东西?
File.WriteAllBytes("application.log", new byte[] { 1, 2, 3 });
File.WriteAllLines("application.log", new string[] { "1", "2", "3" });
File.WriteAllText("application.log", "here is some context");
【讨论】:
试试BinaryWriter。
【讨论】: