开发者

Read binary data from Console.In

Is there any way to read binary data from stdin in C#?

In my problem I have a program which is started and receives binary data on stdin. Basically: C:>myImageReader < someImage.jpg

And I would like to write a program like:

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

However Console.In is not a Stream, it's开发者_JS百科 a TextReader. (And if I attempt to read to char[], the TextReader interprets the data, not allowing me to get access to the raw bytes.)

Anyone got a good idea on how get access to the actual binary input?

Cheers, Leif


To read binary, the best approach is to use the raw input stream - here showing something like "echo" between stdin and stdout:

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


What about using a parameter that specifies the pathname to the file and you open the file for Binary input in the code?

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜