从 Console.In 读取二进制数据

18

有没有办法在C#中从stdin读取二进制数据?

我所面临的问题是我有一个程序,它启动并在stdin上接收二进制数据。 基本上是这样的: C:>myImageReader < someImage.jpg

而我想写一个类似于:

static class Program
{
    static void Main()
    {
        Image img = new Bitmap(Console.In);
        ShowImage(img);
    }
}

然而,Console.In不是一个Stream,它是一个TextReader。(如果我尝试读取char[],TextReader会解释数据,不允许我访问原始字节。)

有人有好的想法如何访问实际的二进制输入吗?

谢谢, Leif

2个回答

32

要读取二进制文件,最好的方法是使用原始输入流 - 在这里,类似于在标准输入和标准输出之间使用“echo”:

using (Stream stdin = Console.OpenStandardInput())
{
   using (Stream stdout = Console.OpenStandardOutput())
   {
      byte[] buffer = new byte[2048];
      int bytes;
      while ((bytes = stdin.Read(buffer, 0, buffer.Length)) > 0) {
         stdout.Write(buffer, 0, bytes);
      }
   }
}

嗯,我本以为 Console.OpenStandardInput() 会返回一个 TextReader 而不是一个 Stream - Powerlord
1
注意,从命令行管道传输文件会以文本模式打开它们,因此您无法使用二进制数据! - Noldorin
2
我们真的需要将标准输出流包含在using语句中吗? - SerG
@Marc使用byte[2048]会将二进制内容限制在2gib大小吗? - Lime
@William 不,它并不是这样的。我认为你对某些事情感到困惑了。byte[2048] 只意味着它每次最多读取 2048 字节(2 KB)。 - Timwi

-1

使用一个指定文件路径的参数,在代码中以二进制输入打开文件怎么样?

static class Program
{
    static int Main(string[] args)
    {
        // Maybe do some validation here
        string imgPath = args[0];

        // Create Method GetBinaryData to return the Image object you're looking for based on the path.
        Image img = GetBinaryData(imgPath);
        ShowImage(img);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接