The complete code is as follows:
Introduce namespace:
Copy codeThe Code is as follows: using System. IO;
Complete code:Copy codeThe Code is as follows: 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 = http://www.jb51.net/andrew-blog/archive/2011/12/02/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:
In this example, when you use the Write method of the BinaryWriter object to Write a Double-type variable aDouble to a file, because the parameter is of the Double type, you can call the reload form of Write (Double, write an 8-byte floating point data to the file stream. In contrast, the ReadDouble () method is used to read 8-byte floating point values from the current stream.
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.