Reputation: 4516
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.
Upvotes: 1
Views: 2818
Reputation: 63
There is also the method System.Console.OpenStandardOutput()
which retrieves the binary standard output stream. You can use that to do something like
byte[] bytes = GetBytes();
Console.OpenStandardOutput().Write(bytes, 0, bytes.Length);
Upvotes: 0
Reputation: 546043
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 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 byte
:new byte[] { 0xFF }
is an invalid UTF-16 code sequence.
Upvotes: 3
Reputation: 35726
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.
Upvotes: 0