Stream to write strings and byte[] arrays?
What is the stream class to use for writing to the file strings and byte[] arrays? File needs to be opened to append or created new if it is absent.
using (Stream s = new Stream("a开发者_Python百科pplication.log")
{
s.Write("message")
s.Write(new byte[] { 1, 2, 3, 4, 5 });
}
use the BinaryWriter-Class
using (Stream s = new Stream("application.log")
{
using(var b = new BinaryWriter(s))
{
b.Write(new byte[] { 1, 2, 3, 4, 5 });
}
}
or as Tim Schmelter suggested (thanks) just 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);
}
this one will append or create the file if needed but the BinaryWriter is nicer to use.
Try using a BinaryWriter? http://msdn.microsoft.com/en-us/library/system.io.binarywriter.aspx
Maybe you need something simplier in your case?
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");
Try BinaryWriter.
精彩评论