Csharp/CSharp Tutorial/File Directory Stream/BinaryReader

Материал из .Net Framework эксперт
Версия от 15:20, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

BinaryReader

C# defines two binary stream classes that can be used to read and write binary data directly.

  1. BinaryReader.
  2. BinaryWriter.

A BinaryReader is a wrapper around a byte stream that handles the reading of binary data.

Method Description int Read() Returns an integer representation of the next available character. Returns -1 when the end of the file is encountered. int Read(byte[ ] buf, int offset, int num) Attempts to read up to num bytes into buf starting at buf[offset], returning the number of bytes successfully read. int Read(char[ ] buf, int offset, int num) Attempts to read up to num characters into buf starting at buf[offset], returning the number of characters successfully read.

Commonly Used Input Methods Defined by BinaryReader

Method Description bool ReadBoolean() Reads a bool. byte ReadByte() Reads a byte. sbyte ReadSByte() Reads an sbyte byte[] ReadBytes(int num) Reads num bytes and returns them as an array. char ReadChar() Reads a char. char[] ReadChar(int num) Reads num characteds and returns them as an array double ReadDouble() Reads a double float ReadSingle() Reads a float short ReadInt16() Reads a short int ReadInt32() Reads an int long ReadInt64() Reads a long ushort ReadUInt16() Reads a ushort uint ReadUInt32() Reads a uint ulong ReadUInt64() Reads a ulong string ReadString() Reads a string that has been written using a BinaryWriter.

Read decimal, strings and char from a binary file using the BinaryReader

<source lang="csharp">using System; using System.IO; static class MainClass {

   static void Main()
   {
       // Create a new file and writer.
       using (FileStream fs = new FileStream("test.bin", FileMode.Create))
       {
           using (BinaryWriter w = new BinaryWriter(fs))
           {
               // Write a decimal, two strings, and a char.
               w.Write(124.23M);
               w.Write("Test string");
               w.Write("Test string 2");
               w.Write("!");
           }
       }
       using (FileStream fs = new FileStream("test.bin", FileMode.Open))
       {
           using (StreamReader sr = new StreamReader(fs))
           {
               // Read the data and convert it to the appropriate data type.
               fs.Position = 0;
               using (BinaryReader br = new BinaryReader(fs))
               {
                   Console.WriteLine(br.ReadDecimal());
                   Console.WriteLine(br.ReadString());
                   Console.WriteLine(br.ReadString());
                   Console.WriteLine(br.ReadChar());
               }
           }
       }
   }

}</source>

124.23
Test string
Test string 2
!

Reset the file pointer to the start

<source lang="csharp">using System; using System.IO; static class MainClass {

   static void Main()
   {
       // Create a new file and writer.
       using (FileStream fs = new FileStream("test.bin", FileMode.Create))
       {
           using (BinaryWriter w = new BinaryWriter(fs))
           {
               // Write a decimal, two strings, and a char.
               w.Write(124.23M);
               w.Write("Test string");
               w.Write("Test string 2");
               w.Write("!");
           }
       }
       using (FileStream fs = new FileStream("test.bin", FileMode.Open))
       {
           using (StreamReader sr = new StreamReader(fs))
           {
               using (BinaryReader br = new BinaryReader(fs))
               {
                   Console.WriteLine(br.ReadDecimal());
                   Console.WriteLine(br.ReadString());
                   Console.WriteLine(br.ReadString());
                   Console.WriteLine(br.ReadChar());
               }
               // Read the data and convert it to the appropriate data type.
               fs.Position = 0;
               using (BinaryReader br = new BinaryReader(fs))
               {
                   Console.WriteLine(br.ReadDecimal());
                   Console.WriteLine(br.ReadString());
                   Console.WriteLine(br.ReadString());
                   Console.WriteLine(br.ReadChar());
               }
           }
       }
   }

}</source>

124.23
Test string
Test string 2
!
Unhandled Exception: System.ObjectDisposedException: Cannot access a closed file.
   at System.IO.__Error.FileNotOpen()
   at System.IO.FileStream.Seek(Int64 offset, SeekOrigin origin)
   at System.IO.FileStream.set_Position(Int64 value)
   at MainClass.Main()

Use BinaryReader to read file in binary format

<source lang="csharp">using System; using System.IO; class MainClass {

 public static void Main() 
 {
   FileStream outStream = File.Create("c:\\BinaryTest.dat");
   BinaryWriter bw = new BinaryWriter(outStream);
   bw.Write( (int) 3);
   bw.Write( (decimal) 4.5);
   string s = "Test String";
   bw.Write(s);
   bw.Flush();
   bw.Close();
   FileStream inStream = File.OpenRead("c:\\BinaryTest.dat");
   BinaryReader br = new BinaryReader(inStream);
   int i = br.ReadInt32();
   decimal d = br.ReadDecimal();
   string s2 = br.ReadString();
   Console.WriteLine(i);
   Console.WriteLine(d);
   Console.WriteLine(s2);
   br.Close();
 }

}</source>

3
4.5
Test String