Csharp/CSharp Tutorial/File Directory Stream/BinaryWriter

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Binary Writer Reader

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
  class Program
  {
    static void Main(string[] args)
    {
      FileInfo f = new FileInfo("BinFile.dat");
      using (BinaryWriter bw = new BinaryWriter(f.OpenWrite()))
      {
        double aDouble = 1234.67;
        int anInt = 34567;
        string aString = "A, B, C";
        bw.Write(aDouble);
        bw.Write(anInt);
        bw.Write(aString);
      }
      using (BinaryReader br = new BinaryReader(f.OpenRead()))
      {
        Console.WriteLine(br.ReadDouble());
        Console.WriteLine(br.ReadInt32());
        Console.WriteLine(br.ReadString());
      }
    }
  }

Commonly Used Output Methods Defined by BinaryWriter

Method Description void Write(sbyte val) Writes a signed byte. void Write(byte val) Writes an unsigned byte. void Write(byte[ ] buf) Writes an array of bytes. void Write(short val) Writes a short integer. void Write(ushort val) Writes an unsigned short integer. void Write(int val) Writes an integer. void Write(uint val) Writes an unsigned integer. void Write(long val) Writes a long integer. void Write(ulong val) Writes an unsigned long integer. void Write(float val) Writes a float. void Write(double val) Writes a double. void Write(char val) Writes a character. void Write(char[ ] buf) Writes an array of characters. void Write(string val) Writes a string using its internal representation, which includes a length specifier.

Move internal position for a BinaryWriter

using System;
using System.IO;
public class MainClass
{
    public static int Main(string[] args)
    {
    Console.WriteLine("***** Creating a file and writing binary data *****");
    FileStream myFStream = new FileStream("temp.dat", FileMode.OpenOrCreate,FileAccess.ReadWrite);
    
    BinaryWriter binWrit = new BinaryWriter(myFStream);
    binWrit.Write("Hello as binary info...");
    
    int myInt = 9;
    float myFloat = 9.8F;
    bool myBool = false;
    char[] myCharArray = {"H", "e", "l", "l", "o"};
    
    binWrit.Write(myInt);
    binWrit.Write(myFloat);
    binWrit.Write(myBool);
    binWrit.Write(myCharArray);
      
      binWrit.BaseStream.Position = 0;
    Console.WriteLine("Reading binary data...");
    BinaryReader binRead = new BinaryReader(myFStream);
    int temp = 0;
    while(binRead.PeekChar() != -1)
    {
      Console.Write(binRead.ReadByte());  
      temp = temp + 1;
      if(temp ==  5)
      {
        temp = 0;
        Console.WriteLine();
      }
    }
    binWrit.Close();
    binRead.Close();
    myFStream.Close();
        return 0;
    }
}
***** Creating a file and writing binary data *****
Reading binary data...
2372101108108
111329711532
9810511097114
12132105110102
1114646469
000205204
2865072101
108108111

Use BinaryWriter to save data in binary format

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();
  }
}
3
4.5
Test String

Write and read back binary data

using System; 
using System.IO;  
 
class MainClass { 
  public static void Main() { 
    BinaryWriter dataOut; 
    BinaryReader dataIn; 
 
    int i = 10; 
    double d = 1.56; 
    bool b = true; 
 
    try { 
      dataOut = new BinaryWriter(new FileStream("testdata", FileMode.Create)); 
    } 
    catch(IOException exc) { 
      Console.WriteLine(exc.Message + "\nCannot open file."); 
      return; 
    } 
 
    try { 
      Console.WriteLine("Writing " + i); 
      dataOut.Write(i);  
 
      Console.WriteLine("Writing " + d); 
      dataOut.Write(d); 
 
      Console.WriteLine("Writing " + b); 
      dataOut.Write(b); 
 
      Console.WriteLine("Writing " + 12.2 * 7.4); 
      dataOut.Write(12.2 * 7.4); 
 
    } 
    catch(IOException exc) { 
      Console.WriteLine(exc.Message + "\nWrite error."); 
    } 
 
    dataOut.Close(); 
 
    Console.WriteLine(); 
 
    try { 
      dataIn = new BinaryReader(new FileStream("testdata", FileMode.Open)); 
    } 
    catch(FileNotFoundException exc) { 
      Console.WriteLine(exc.Message + "\nCannot open file."); 
      return; 
    } 
 
    try { 
      i = dataIn.ReadInt32(); 
      Console.WriteLine("Reading " + i); 
 
      d = dataIn.ReadDouble(); 
      Console.WriteLine("Reading " + d); 
 
      b = dataIn.ReadBoolean(); 
      Console.WriteLine("Reading " + b); 
 
      d = dataIn.ReadDouble(); 
      Console.WriteLine("Reading " + d); 
    } 
    catch(IOException exc) { 
      Console.WriteLine(exc.Message + "Read error."); 
    } 
 
    dataIn.Close();  
  } 
}
Writing 10
Writing 1.56
Writing True
Writing 90.28
Reading 10
Reading 1.56
Reading True
Reading 90.28

Write decimal, strings and char to a file using the BinaryWriter

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))
            {
                Console.WriteLine(sr.ReadToEnd());
                Console.WriteLine();
            }
        }
    }
}
Test string 2! Test string

Write/Read int, float, char array and bool to a binary file using BinaryWriter

using System;
using System.IO;
public class MainClass
{
    public static int Main(string[] args)
    {
    Console.WriteLine("***** Creating a file and writing binary data *****");
    FileStream myFStream = new FileStream("temp.dat", FileMode.OpenOrCreate,FileAccess.ReadWrite);
    
    BinaryWriter binWrit = new BinaryWriter(myFStream);
    binWrit.Write("Hello as binary info...");
    
    int myInt = 9;
    float myFloat = 9.8F;
    bool myBool = false;
    char[] myCharArray = {"H", "e", "l", "l", "o"};
    
    binWrit.Write(myInt);
    binWrit.Write(myFloat);
    binWrit.Write(myBool);
    binWrit.Write(myCharArray);
      
      binWrit.BaseStream.Position = 0;
    Console.WriteLine("Reading binary data...");
    BinaryReader binRead = new BinaryReader(myFStream);
    int temp = 0;
    while(binRead.PeekChar() != -1)
    {
      Console.Write(binRead.ReadByte());  
      temp = temp + 1;
      if(temp ==  5)
      {
        temp = 0;
        Console.WriteLine();
      }
    }
    binWrit.Close();
    binRead.Close();
    myFStream.Close();
        return 0;
    }
}
***** Creating a file and writing binary data *****
Reading binary data...
2372101108108
111329711532
9810511097114
12132105110102
1114646469
000205204
2865072101
108108111