Export (0) Print
Expand All

BinaryReader Class

Reads primitive data types as binary values in a specific encoding.

Namespace: System.IO
Assembly: mscorlib (in mscorlib.dll)

[ComVisibleAttribute(true)] 
public class BinaryReader : IDisposable
/** @attribute ComVisibleAttribute(true) */ 
public class BinaryReader implements IDisposable
ComVisibleAttribute(true) 
public class BinaryReader implements IDisposable

The following table lists examples of other typical or related I/O tasks.

To do this...

See the example in this topic...

Create a text file.

How to: Write Text to a File

Write to a text file.

How to: Write Text to a File

Read from a text file.

How to: Read Text from a File

Read from a binary file.

How to: Read and Write to a Newly Created Data File

Write to a binary file.

How to: Read and Write to a Newly Created Data File

The following code example demonstrates how to store and retrieve application settings in a file.

using System;
using System.IO;
using System.Security.Permissions;

class Test
{
    static void Main()
    {
        // Load application settings.
        AppSettings appSettings = new AppSettings();
        Console.WriteLine("App settings.\nAspect Ratio: {0}, " +
            "Lookup directory: {1},\nAuto save time: {2} minutes, " +
            "Show status bar: {3}\n", 
            new Object[4]{appSettings.AspectRatio.ToString(), 
            appSettings.LookupDir, appSettings.AutoSaveTime.ToString(),
            appSettings.ShowStatusBar.ToString()});

        // Change the settings.
        appSettings.AspectRatio   = 1.250F;
        appSettings.LookupDir     = @"C:\Temp";
        appSettings.AutoSaveTime  = 10;
        appSettings.ShowStatusBar = true;

        // Save the new settings.
        appSettings.Close();
    }
}

// Store and retrieve application settings.
class AppSettings
{
    const string fileName = "AppSettings#@@#.dat";
    float  aspectRatio;
    string lookupDir;
    int    autoSaveTime;
    bool   showStatusBar;

    public float AspectRatio
    {
        get{ return aspectRatio; }
        set{ aspectRatio = value; }
    }

    public string LookupDir
    {
        get{ return lookupDir; }
        set{ lookupDir = value; }
    }

    public int AutoSaveTime
    {
        get{ return autoSaveTime; }
        set{ autoSaveTime = value; }
    }

    public bool ShowStatusBar
    {
        get{ return showStatusBar; }
        set{ showStatusBar = value; }
    }

    public AppSettings()
    {
        // Create default application settings.
        aspectRatio   = 1.3333F;
        lookupDir     = @"C:\AppDirectory";
        autoSaveTime  = 30;
        showStatusBar = false;

        if(File.Exists(fileName))
        {
            BinaryReader binReader = 
                new BinaryReader(File.Open(fileName, FileMode.Open));
            try
            {
                // If the file is not empty, 
                // read the application settings.
                if(binReader.PeekChar() != -1)
                {
                    aspectRatio   = binReader.ReadSingle();
                    lookupDir     = binReader.ReadString();
                    autoSaveTime  = binReader.ReadInt32();
                    showStatusBar = binReader.ReadBoolean();
                }
            }

            // If the end of the stream is reached before reading
            // the four data values, ignore the error and use the
            // default settings for the remaining values.
            catch(EndOfStreamException e)
            {
                Console.WriteLine("{0} caught and ignored. " + 
                    "Using default values.", e.GetType().Name);
            }
            finally
            {
                binReader.Close();
            }
        }

    }

    // Create a file and store the application settings.
    public void Close()
    {
        using(BinaryWriter binWriter = 
            new BinaryWriter(File.Open(fileName, FileMode.Create)))
        {
            binWriter.Write(aspectRatio);
            binWriter.Write(lookupDir);
            binWriter.Write(autoSaveTime);
            binWriter.Write(showStatusBar);
        }
    }
}

import System.*;
import System.IO.*;
import System.Security.Permissions.*;

class Test
{   
    public static void main(String[] args)
    {        
        // Load application settings.
        AppSettings appSettings = new AppSettings();
        Console.WriteLine("App settings.\nAspect Ratio: {0}, "
            + "Lookup directory: {1},\nAuto save time: {2} minutes, "
            + "Show status bar: {3}\n",
            new Object[]{System.Convert.ToString(appSettings.get_AspectRatio()),
            appSettings.get_LookupDir(),
            System.Convert.ToString(appSettings.get_AutoSaveTime()),
            System.Convert.ToString(appSettings.get_ShowStatusBar())});

        // Change the settings.
        appSettings.set_AspectRatio(1.25F);
        appSettings.set_LookupDir("C:\\Temp");
        appSettings.set_AutoSaveTime ( 10);
        appSettings.set_ShowStatusBar( true);

        // Save the new settings.
        appSettings.Close();
    } //main
} //Test

// Store and retrieve application settings.
class AppSettings
{
    private String fileName = "AppSettings#@@#.dat";
    private float aspectRatio;
    private String lookupDir;
    private int autoSaveTime;
    private boolean showStatusBar;

    /** @property 
     */
    public float get_AspectRatio()
    {
        return aspectRatio ;
    }//get_AspectRatio

    /** @property 
     */
    public void set_AspectRatio ( float value )
    {
        aspectRatio = value;
    }//set_AspectRatio

    /** @property 
     */
    public String get_LookupDir()
    {
        return lookupDir ;
    }//get_LookupDir

    /** @property 
     */
    public void set_LookupDir ( String value )
    {
        lookupDir = value;
    }//set_LookupDir

    /** @property
     */
    public int get_AutoSaveTime()
    {
        return autoSaveTime ;
    }//get_AutoSaveTime

    /** @property
     */
    public void set_AutoSaveTime ( int value )
    {
        autoSaveTime = value;
    }//set_AutoSaveTime

    /** @property
     */
    public boolean get_ShowStatusBar()
    {
        return showStatusBar ;
    }//get_ShowStatusBar

    /** @property
     */
    public void set_ShowStatusBar ( boolean value )
    {
        showStatusBar = value;
    }//set_ShowStatusBar
   
    public AppSettings()
    {
        // Create default application settings.
        aspectRatio = 1.3333F;
        lookupDir = "C:\\AppDirectory";
        autoSaveTime = 30;
        showStatusBar = false;

        if ( File.Exists(fileName) ) {
            BinaryReader binReader =
                new BinaryReader(File.Open(fileName, FileMode.Open));
            try {
                // If the file is not empty, 
                // read the application settings.
                if ( binReader.PeekChar() !=-1  ) {
                    aspectRatio = binReader.ReadSingle();
                    lookupDir = binReader.ReadString();
                    autoSaveTime = binReader.ReadInt32();
                    showStatusBar = binReader.ReadBoolean();
                }
            }

            // If the end of the stream is reached before reading
            // the four data values, ignore the error and use the
            // default settings for the remaining values.
            catch(EndOfStreamException e) {
                Console.WriteLine("{0} caught and ignored. "
                    + "Using default values.", e.GetType().get_Name());
            }
            finally {
                binReader.Close();
            }
        }
    } //AppSettings
   
    // Create a file and store the application settings.
    public void Close()
    {
        BinaryWriter binWriter = 
            new BinaryWriter(File.Open(fileName, FileMode.Create));
        try {
            binWriter.Write(aspectRatio);
            binWriter.Write(lookupDir);
            binWriter.Write(autoSaveTime);
            binWriter.Write(showStatusBar);
        }
        finally {
            if ( binWriter != null ) {
                binWriter= null;
            }
        }
    } //Close 
} //AppSettings

System.Object
  System.IO.BinaryReader

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft