Question

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.

Was it helpful?

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.

OTHER TIPS

Not just

File.WriteAllBytes(filepath, GetBytes())

or you could do,

using (var writer = new StreamWriter(filepath))
{
    var bytes = GetBytes();
    writer.BaseStream.Write(bytes, 0, bytes.Length)
};

Once you pass the StreamWriter to SetOut it exposes only the base TextWriter which does not allow access to the internal stream. This makes sense because Console is designed for providing output to the user. I guess its non standard to output arbritary binary to the console.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top