Read and Write a Binary File : Binary Read Write « File Stream « C# / C Sharp






Read and Write a Binary File

   

using System;
using System.IO;

public class BinaryFileTest {

    private static void Main() {
        FileStream fs = new FileStream("test.dat", FileMode.Create);
        BinaryWriter w = new BinaryWriter(fs);

        w.Write(1.2M);
        w.Write("string");
        w.Write("string 2");
        w.Write('!');
        w.Flush();
        w.Close();
        fs.Close();

        fs = new FileStream("test.dat", FileMode.Open);
        StreamReader sr = new StreamReader(fs);
        Console.WriteLine(sr.ReadToEnd());
        fs.Position = 0;
        BinaryReader br = new BinaryReader(fs);
        Console.WriteLine(br.ReadDecimal());
        Console.WriteLine(br.ReadString());
        Console.WriteLine(br.ReadString());
        Console.WriteLine(br.ReadChar());
        fs.Close();

    }
}

   
    
  








Related examples in the same category

1.Binary Writer Reader
2.new BinaryReader(stream)
3.StreamWriter and BinaryWriter
4.new BinaryWriter(stream) and Write method
5.Creating a sequential-access file
6.Reading a sequential-access fileReading a sequential-access file
7.BinaryWriter and BinaryReader classes for the writing and reading of primitive typesBinaryWriter and BinaryReader classes for the writing and reading of primitive types
8.Working with the BinaryWriter Class
9.Working with the BinaryReader ClassWorking with the BinaryReader Class
10.File pointer move and read binary file
11.Write and then read back binary dataWrite and then read back binary data
12.Use BinaryReader and BinaryWriter to implement a simple inventory programUse BinaryReader and BinaryWriter to implement 
   a simple inventory program
13.Read the data from a file and desiralize it
14.Read Struct out of a file with BinaryReader
15.extends BinaryReader
16.Write a value at a given position. Used to write a size of data in an earlier located header.