How to: Read a Binary File
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

How to: Read a Binary File 

The following code example demonstrates reading binary data from a file. Two classes from the System.IO namespace are used: FileStream and BinaryReader. FileStream represents the actual file. BinaryReader provides an interface to the stream that allows binary access.

The following code example uses a file created by the code in How to: Write a Binary File called data.bin.


// binary_read.cpp
// compile with: /clr
using namespace System;
using namespace System::IO;

int main() 
   String^ fileName = "data.bin";
      FileStream^ fs = gcnew FileStream(fileName, FileMode::Open);
      BinaryReader^ br = gcnew BinaryReader(fs);

      Console::WriteLine("contents of {0}:", fileName);
      while (br->BaseStream->Position < br->BaseStream->Length)

      fs->Close( );
   catch (Exception^ e)
      if (dynamic_cast<FileNotFoundException^>(e))
         Console::WriteLine("File '{0}' not found", fileName);
         Console::WriteLine("Exception: ({0})", e);
      return -1;
   return 0;

See Also

© 2015 Microsoft