How to write a binary file in C#

Writing Binary to a Stream
 
The Write overloaded method is used to write primitive data types to a stream. The Write method can write a Boolean, Byte, Char, Decimal, Double, and Integer data types. 
 
The following code snippet creates a BinaryWriter and writes string, Boolean, integer and double data types to the stream. 
  1. string authorName = "Mahesh Chand";  
  2. int age = 30;  
  3. string bookTitle = "ADO.NET Programming using C#";  
  4. bool mvp = true;  
  5. double price = 54.99;  
  6.   
  7. using (BinaryWriter binWriter =  
  8.     new BinaryWriter(File.Open(fileName, FileMode.Create)))  
  9. {  
  10.     // Write string   
  11.     binWriter.Write(authorName);  
  12.     // Write string   
  13.     // Write integer  
  14.     binWriter.Write(age);  
  15.     binWriter.Write(bookTitle);  
  16.     // Write boolean  
  17.     binWriter.Write(mvp);  
  18.     // Write double   
  19.     binWriter.Write(price);  
  20. }  
Learn More: Create a binary file in C#