1

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("application.log")
{
    s.Write("message")
    s.Write(new byte[] { 1, 2, 3, 4, 5 });
}
0

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you too (as for the quick response ... yeah the shorter/slower one got the "answered" ... wonder why?)
I do not follow that rule as you can see from my questions, but you may try to quickly answer the question with a short comment, and then edit it later with more details, in any case I voted you too :)
7

Try using a BinaryWriter? http://msdn.microsoft.com/en-us/library/system.io.binarywriter.aspx

Comments

1

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

Comments

0

Try BinaryWriter.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.