8

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?

1
  • StandardOutput.BaseStream = a stream used to read the output of the application, not usable for your case. Commented Oct 30, 2009 at 0:46

2 Answers 2

18

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Async version with .NET 7 await using Stream stdout = Console.OpenStandardOutput(); await stdout.WriteAsync( buf );
2

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);
    }
}

1 Comment

FYI - You might be interested in LINQPad. It's a great little tool for quickly writing and testing code snippets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.