Search code examples
c#streamconsoletextwriter

How can you use Console.Out to write a byte[] to a file?


In java you can do this:

File file = new File(filepath);
PrintStream pstream = new PrintStream(new FileOutputStream(file));
System.setOut(pstream);

byte[] bytes = GetBytes();
System.out.write(bytes);

I want to do something similar in C#. I tried this but it didn't work:

StreamWriter writer = new StreamWriter(filepath);
Console.SetOut(writer);

byte[] bytes = GetBytes();
Console.Out.Write(bytes);

It looks like the main problem here is that the Write method does not accept an array of bytes as an argument.

I know that I could get away with File.WriteAllBytes(filepath, bytes), but I would like to keep the C# code as close as possible to the original, java code.


Solution

  • I know that I could get away with File.WriteAllBytes(filepath, bytes), but I would like to keep the C# code as close as possible to the original, java code.

    The Java code does something you’re not supposed to do: it’s writing binary data to the standard output, and standard streams aren’t designed for binary data, they’re designed with text in mind. .NET does “the right thing” here and gives you a text interface, not a binary data interface.

    The correct method is therefore to write the data to a file directly, not to standard output.

    As a workaround you can fake it and convert the bytes to characters using an invariant encoding for the range of byte: Doesn’t work since the “invariant” encoding for .NET strings is UTF-16 which doesn’t accept every byte input as valid; for instance, the byte array new byte[] { 0xFF } is an invalid UTF-16 code sequence.