2011-08-31 143 views
0

用于写入文件字符串和byte []数组的流类是什么? 如果文件不存在,则需要打开文件以追加或创建新文件。流写入字符串和byte []数组?

using (Stream s = new Stream("application.log") 
{ 
    s.Write("message") 
    s.Write(new byte[] { 1, 2, 3, 4, 5 }); 
} 

回答

4

使用BinaryWriter -Class

using (Stream s = new Stream("application.log") 
{ 
    using(var b = new BinaryWriter(s)) 
    { 
    b.Write(new byte[] { 1, 2, 3, 4, 5 }); 
    } 
} 

或添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是更好使用。

+0

感谢您的建议 –

+0

太感谢您(作为快速反应...是啊短于/慢一个拿到“回答” ......不知为什么?)我 – Carsten

+0

不要遵循这个规则,因为你可以从我的问题中看到,但你可以尝试用简短的评论快速回答这个问题,然后稍后再编辑它以提供更多详细信息,无论如何我也会投你一票:) –

0

也许你需要一些简单的东西在你的情况?

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"); 
+0

是的,那也是听起来很有趣 –