chris
chris

Reputation:

Write binary data to stdout in c#?

I'm trying to write a quick cgi app in c#. I need to get to the stdout stream and write some binary data. The only thing I can find to do this is Console.Write, which takes text. I've also tried

Process.GetCurrentProcess().StandardOutput.BaseStream.Write 

which doesn't work either. Is this even possible?

Upvotes: 8

Views: 4923

Answers (2)

Edward Ned Harvey
Edward Ned Harvey

Reputation: 7031

Wow, it's a bummer this question wasn't answered in 5 years. Viewed 1800 times.

OpenStandardOutput() has existed since .Net 4.0

using (Stream myOutStream = Console.OpenStandardOutput())
{
    myOutStream.Write(buf, 0, buf.Length);
}

Upvotes: 18

Peter McG
Peter McG

Reputation: 19045

Something like the following (very quick example written in notepad):

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class MyObject {
    public int n1 = 0;
    public int n2 = 0;
    public String str = null;
}

public class Example
{
    public static void Main()
    {
        MyObject obj = new MyObject();
        obj.n1 = 1;
        obj.n2 = 24;
        obj.str = "Some String";
        BinaryFormatter formatter = new BinaryFormatter();

        StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
        sw.AutoFlush = true;
        Console.SetOut(sw);

        formatter.Serialize(sw.BaseStream, obj);
    }
}

Upvotes: 2

Related Questions