Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read binary data from Console.In

Tags:

c#

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

like image 778
leiflundgren Avatar asked Oct 13 '09 19:10

leiflundgren


People also ask

How do I read a binary file in R?

To read a binary file, we select appropriate values of column names and column values. We use the file name and connection mode rb to create the connection opening. rb : the mode of connection opening. r means to read and b means binary.

How do I decode a binary file?

You can use Notepad++ install the plugin for hex editor. Once you have that, all you need to do is some kind of combination and permutation, depending upon what kind of data is held in you binary file (also while doing it keep in mind the byte order little or big endian).


1 Answers

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);
      }
   }
}
like image 58
Marc Gravell Avatar answered Oct 16 '22 08:10

Marc Gravell