HI WELCOME TO SIRIS

C# BinaryReader

Leave a Comment
C# BinaryReader class is used to read binary information from stream. It is found in System.IO namespace. It also supports reading string in specific encoding.

C# BinaryReader Example

Let's see the simple example of BinaryReader class which reads data from dat file.
  1. using System;  
  2. using System.IO;  
  3. namespace BinaryWriterExample  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             WriteBinaryFile();  
  10.             ReadBinaryFile();  
  11.             Console.ReadKey();  
  12.         }  
  13.         static void WriteBinaryFile()  
  14.         {  
  15.             using (BinaryWriter writer = new BinaryWriter(File.Open("e:\\binaryfile.dat", FileMode.Create)))  
  16.             {  
  17.                  
  18.                 writer.Write(12.5);  
  19.                 writer.Write("this is string data");  
  20.                 writer.Write(true);  
  21.             }  
  22.         }  
  23.         static void ReadBinaryFile()  
  24.         {  
  25.             using (BinaryReader reader = new BinaryReader(File.Open("e:\\binaryfile.dat", FileMode.Open)))  
  26.             {  
  27.                 Console.WriteLine("Double Value : " + reader.ReadDouble());  
  28.                 Console.WriteLine("String Value : " + reader.ReadString());  
  29.                 Console.WriteLine("Boolean Value : " + reader.ReadBoolean());  
  30.             }  
  31.         }  
  32.     }  
  33. }  
Output:
Double Value : 12.5
String Value : this is string data
Boolean Value : true

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.