【问题标题】:Read binary data from Console.In从 Console.In 读取二进制数据
【发布时间】:2009-10-13 19:28:10
【问题描述】:

有什么方法可以在 C# 中从标准输入读取二进制数据?

在我的问题中,我有一个程序已启动并在标准输入上接收二进制数据。 基本上: C:>myImageReader < someImage.jpg

我想写一个类似的程序:

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

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

有人知道如何访问实际的二进制输入吗?

干杯, 雷夫

【问题讨论】:

    标签: c#


    【解决方案1】:

    要读取二进制文件,最好的方法是使用原始输入流 - 这里显示了标准输入和标准输出之间的“回声”:

    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
    • 请注意,命令行中的管道文件以文本模式打开它们,因此您不能使用二进制数据!
    • 我们真的需要将标准输出流封装到using 语句中吗?
    • @Marc 不使用 byte[2048] 将二进制内容的大小限制为 2gibs?
    • @William 不,它没有。我认为你对某些事情感到困惑。 byte[2048] 仅表示一次最多读取 2048 个字节(2 KB)。
    【解决方案2】:

    如何使用指定文件路径名的参数并在代码中打开文件以进行二进制输入?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-24
      • 2011-11-27
      • 1970-01-01
      • 2010-09-14
      • 1970-01-01
      • 2010-12-08
      • 2014-03-24
      • 2015-06-27
      相关资源
      最近更新 更多