2011-08-31 78 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

是的,那也是聽起來很有趣 –