tags:

views:

542

answers:

1

I'm trying to stream binary data to the standard output in .NET. However you can only write char using the Console class. I want to use it with redirection. Is there a way to do this?

+4  A: 

You can access the output stream using Console.OpenStandardOutput.

    static void Main(string[] args) {
        MemoryStream data = new MemoryStream(Encoding.UTF8.GetBytes("Some data"));
        using (Stream console = Console.OpenStandardOutput()) {
            StreamCopy(console, data);
        }
    }

    public static void StreamCopy(Stream dest, Stream src) {
        byte[] buffer = new byte[4 * 1024];
        int n = 1;
        while (n > 0) {
            n = src.Read(buffer, 0, buffer.Length);
            dest.Write(buffer, 0, n);
        }
        dest.Flush();
    }
Frank Krueger