16

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 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

leiflundgren
  • 2,876
  • 7
  • 35
  • 53

2 Answers2

30

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);
      }
   }
}
Eray Balkanli
  • 7,752
  • 11
  • 48
  • 82
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Hmm, I would have assumed `Console.OpenStandardInput()` would return a `TextReader` rather than a `Stream`. – Powerlord Oct 13 '09 at 19:42
  • 1
    Beware however that piping files from the command line opens them in text mode, so you cannot use binary data then! – Noldorin Sep 26 '11 at 16:42
  • 2
    Do we really need to enclose the standard output stream into the `using` statement? – SerG Mar 06 '14 at 09:00
  • @Marc Doesn't using byte[2048] limit the binary content to 2gibs in size? – Lime Aug 05 '15 at 22:32
  • @William No, it doesn’t. I think you’re confused about something. `byte[2048]` only means that it will read at most 2048 bytes (2 KB) at a time. – Timwi Oct 05 '15 at 10:32
-1

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);
    }
}
Joshua Starner
  • 1,573
  • 1
  • 13
  • 13