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
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.
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).
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With