The complete code is as follows:
Introduce namespace:
Using System. IO;
Complete code:
| The code is as follows: |
Copy code |
|
Namespace BinaryStreamApp
{
Class Program
{
Static void Main (string [] args)
{
// Open a binary writer for the file
FileStream fs;
Fs = new FileStream ("C: \ BinFile. dat", FileMode. OpenOrCreate, FileAccess. ReadWrite );
BinaryWriter bw = new BinaryWriter (fs );
// Prepare different types of data
Double aDouble = 1234.56;
Int aInt = 34567;
Char [] aCharArray = {'A', 'B', 'C '};
// Write data using multiple reloads of the Write method
Bw. Write (aDouble );
Bw. Write (aInt );
Bw. Write (aCharArray );
Int length = Convert. ToInt32 (bw. BaseStream. Length );
Fs. Close ();
Bw. Close ();
// Read and output data
Fs = new FileStream ("C: \ BinFile. dat", FileMode. OpenOrCreate, FileAccess. Read );
BinaryReader br = new BinaryReader (fs );
Console. WriteLine (br. ReadDouble (). ToString ());
Console. WriteLine (br. ReadInt32 (). ToString ());
Char [] data = br. ReadChars (length );
For (int I = 0; I <data. Length; I ++)
{
Console. WriteLine ("{0, 7: x}", data [I]);
}
Fs. Close ();
Br. Close ();
Console. ReadLine ();
}
}
} |
Running effect:
When an Int32 variable aInt is written, the system automatically calls the Write (Int32) method and writes a 4-byte signed integer to the file stream. When reading data, the ReadInt32 () method is called, read 4-byte data from a file stream.
It can be seen that the BinaryReader and BinaryWriter objects are very convenient to write and read data of fixed length types such as integer and floating point type to the stream.