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

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

15 c#
13.10.2009 19:28:10

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);
26.02.2018 21:09:52
Hmm, I would have assumed Console.OpenStandardInput() would return a TextReader rather than a Stream.
Powerlord 13.10.2009 19:42:39
Beware however that piping files from the command line opens them in text mode, so you cannot use binary data then!
Noldorin 26.09.2011 16:42:34
Do we really need to enclose the standard output stream into the using statement?
SerG 6.03.2014 09:00:35
@Marc Doesn't using byte[2048] limit the binary content to 2gibs in size?
Lime 5.08.2015 22:32:14
@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 5.10.2015 10:32:40

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);
13.10.2009 19:46:53