BinaryReader
In this chapter you will learn:
Get to know BinaryReader
C# defines two binary stream classes that can be used to read and write binary data directly.
- BinaryReader
- BinaryWriter
A BinaryReader is a wrapper around a byte stream that handles the reading of binary data.
The following lists the commonly Used Input Methods Defined by BinaryReader
Method | Description |
---|---|
int Read() | Returns an integer representation of the next available character. Returns -1 when the end of the file is encountered. |
int Read(byte[ ] buf, int offset, int num) | Attempts to read up to num bytes into buf starting at buf[offset], returning the number of bytes successfully read. |
int Read(char[ ] buf, int offset, int num) | Attempts to read up to num characters into buf starting at buf[offset], returning the number of characters successfully read. |
bool ReadBoolean() | Reads a bool. |
byte ReadByte() | Reads a byte. |
sbyte ReadSByte() | Reads an sbyte |
byte[] ReadBytes(int num) | Reads num bytes and returns them as an array. |
char ReadChar() | Reads a char. |
char[] ReadChar(int num) | Reads num characteds and returns them as an array |
double ReadDouble() | Reads a double |
float ReadSingle() | Reads a float |
short ReadInt16() | Reads a short |
int ReadInt32() | Reads an int |
long ReadInt64() | Reads a long |
ushort ReadUInt16() | Reads a ushort |
uint ReadUInt32() | Reads a uint |
ulong ReadUInt64() | Reads a ulong |
string ReadString() | Reads a string that has been written using a BinaryWriter. |
Example to use BinaryReader to read data
The following codes
reads decimal, strings and char from a binary file using the BinaryReader
.
using System;/*from ja v a 2 s . c o m*/
using System.IO;
static class MainClass
{
static void Main()
{
// Create a new file and writer.
using (FileStream fs = new FileStream("test.bin", FileMode.Create))
{
using (BinaryWriter w = new BinaryWriter(fs))
{
// Write a decimal, two strings, and a char.
w.Write(124.23M);
w.Write("Test string");
w.Write("Test string 2");
w.Write('!');
}
}
using (FileStream fs = new FileStream("test.bin", FileMode.Open))
{
using (StreamReader sr = new StreamReader(fs))
{
// Read the data and convert it to the appropriate data type.
fs.Position = 0;
using (BinaryReader br = new BinaryReader(fs))
{
Console.WriteLine(br.ReadDecimal());
Console.WriteLine(br.ReadString());
Console.WriteLine(br.ReadString());
Console.WriteLine(br.ReadChar());
}
}
}
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter: