Read a binary file byte by byte in CSharp

Description

The following code shows how to read a binary file byte by byte.

Example


using System;/*from  w  w  w  .j ava 2s  .co m*/
using System.Collections.Generic;
using System.Text;
using System.IO;

class Program {
    static void Main(string[] args) {
        FileInfo f = new FileInfo("BinFile.dat");
        BinaryWriter bw = new BinaryWriter(f.OpenWrite());

        Console.WriteLine("Base stream is: {0}", bw.BaseStream);

        double aDouble = 1234.67;
        int anInt = 34567;
        char[] aCharArray = { 'A', 'B', 'C' };

        bw.Write(aDouble);
        bw.Write(anInt);
        bw.Write(aCharArray);
        bw.Close();

        BinaryReader br = new BinaryReader(f.OpenRead());
        int temp = 0;
        while (br.PeekChar() != -1) {
            Console.Write("{0,7:x} ", br.ReadByte());
            if (++temp == 4) {
                Console.WriteLine();
                temp = 0;
            }
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    IO »




File Attribute
File Security
Directory Attribute
Directory Recursive
Binary File
Text Field
Buffered IO
Create Copy Delete Move
CSV
Drive
File System Watcher
Isolated Storage
MemoryStream
Serialize
Zip