BinaryWriter and BinartReader classes are used to operate binary files using I/O streams.
1. BinaryWriter class
The BinaryWriter class writes the primitive type to the stream in binary format and supports writing strings with specific encoding.
Common Methods:
Close to Close the current BinaryWriter and basic stream
Seek sets the position in the current stream
Write writes the value to the current stream
2. BinartReader class
The BinartReader class reads the basic metadata type as a binary value using a specific encoding.
Common Methods:
Close to Close the current Reader and basic stream
Read reads characters from the base stream and improves the current position of the stream.
ReadBytes reads count bytes from the current stream into the byte array and increases the current position by count bytes.
ReadInt32 reads four byte signed integers from the current stream and increases the current position of the stream by four bytes.
ReadString reads a string from the current stream. The character string has a length prefix. 7 is encoded as an integer at a time.
3. instance code: demonstrate how to write and read binary files
Private void button#click (object sender, EventArgs e) {if (textBox1.Text = string. empty) {MessageBox. show ("the file content to be written cannot be blank");} else {// set the format of saving the file saveFileDialog1.Filter = "binary file (*. dat) | *. dat "; if (saveFileDialog1.ShowDialog () = DialogResult. OK) {// use the file name input in the "Save as" dialog box to instantiate the FileStream object FileStream myStream = new FileStream (saveFileDialog1.FileName, FileMode. openOrCreate, FileAccess. readWrite); // use Fil EStream Object Instantiation BinaryWriter binary write Stream object BinaryWriter myWriter = new BinaryWriter (myStream); // write content myWriter to the created file in binary mode. write (textBox1.Text); // close the current binary Write stream myWriter. close (); // Close the current file stream myStream. close (); textBox1.Text = string. empty ;}} private void button2_Click (object sender, EventArgs e) {// set the file opening format openFileDialog1.Filter = "binary file (*. dat) | *. dat "; if (openFileDialog1.ShowDialog () = DialogResult. OK) {TextBox1.Text = string. empty; // use the file name selected in the "open" dialog box to instantiate the FileStream object FileStream myStream = new FileStream (openFileDialog1.FileName, FileMode. open, FileAccess. read); // use the FileStream object to instantiate BinaryReader binary to write the stream object BinaryReader myReader = new BinaryReader (myStream); if (myReader. peekChar ()! =-1) {// read the content in the file in binary format textBox1.Text = myReader. readString ();} // close the current binary read stream myReader. close (); // Close the current file stream myStream. close ();}}