我正在尝试用c#编写一个快速的cgi应用程序。我需要到stdout流并写一些二进制数据。我唯一能找到的就是Console.Write,它接受文本。我也试过了
Process.GetCurrentProcess().StandardOutput.BaseStream.Write
也不起作用。这甚至可能吗?
答案 0 :(得分:9)
OpenStandardOutput()自.Net 4.0以来就已存在
using (Stream myOutStream = Console.OpenStandardOutput())
{
myOutStream.Write(buf, 0, buf.Length);
}
答案 1 :(得分:2)
如下所示(用记事本写的非常快的例子):
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);
}
}