< StreamReader & StreamWriter Program Examples | Main | Chap 3: Threading & Asynchronous >

 


 

 

Chapter 2 Part 16:

Managed I/O - Streams, Readers, and Writers

 

 

What do we have in this chapter 2 Part 16?

  1. BinaryReader and BinaryWriter

  2. C++ BinaryReader and BinaryWriter Program Example

  3. C# BinaryReader and BinaryWriter Program Example

  4. VB .NET BinaryReader and BinaryWriter Program Example

 

 

 

Note: If you want to experience a complete C++ .NET/C++-CLI programming tutorial please jump to Visual C++ .NET programming tutorial.

 

BinaryReader and BinaryWriter

 

The BinaryReader and BinaryWriter stream classes allow you to read and write specific data types to a stream in binary form, which means that the data types are read and written as they’re represented in computer memory. For example, you can write an object of type Int32 and the BinaryWriter will write a 4-byte signed integer to a stream and advance the Position property of the stream by four bytes.

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

 

C++ BinaryReader and BinaryWriter Example

 

Create a new CLR console application project and you might want to use BinaryWriterBinaryReaderCP as the project and solution names.

 

C++ BinaryReader and BinaryWriter Example - CLR console application new project creation

 

Add the following code.

 

 

// BinaryReaderBinaryWriterCP.cpp : main project file.

 

#include "stdafx.h"

 

using namespace System;

using namespace System::IO;

using namespace System::Security::Permissions;

 

// Store and retrieve application settings.

ref class AppSettings

{

            private:

                        static String^ fileName =  "AppSettings#@@#.dat";

                        float aspectRatio;

                        String^ lookupDir;

                        int autoSaveTime;

                        Boolean showStatusBar;

 

            public:

                        property float AspectRatio

                        {

                                    float get()

                                    {

                                                return aspectRatio;

                                    }

                                   

                                    void set( float value )

                                    {

                                                aspectRatio = value;

                                    }

                        }

 

                        property String^ LookupDir

                        {

                                    String^ get()

                                    {

                                                return lookupDir;

                                    }

                                   

                                    void set( String^ value )

                                    {

                                                lookupDir = value;

                                    }

                        }

 

                        property int AutoSaveTime

                        {

                                    int get()

                                    {

                                                return autoSaveTime;

                                    }

                                   

                                    void set( int value )

                                    {

                                                autoSaveTime = value;

                                    }

                        }

                       

                        property Boolean ShowStatusBar

                        {

                                    Boolean get()

                                    {

                                                return showStatusBar;

                                    }

                                   

                                    void set( Boolean value )

                                    {

                                                showStatusBar = value;

                                    }

                        }

                       

                        AppSettings()

                        {

                                    // Create default application settings.

                                    aspectRatio = 1.3333F;

                                    lookupDir =  "C:\\AppDirectory";

                                    autoSaveTime = 30;

                                    showStatusBar = false;

 

                                    Console::WriteLine("Creating default application settings...");

                                    if ( File::Exists( fileName ) )

                                    {

                                                BinaryReader^ binReader = gcnew BinaryReader( File::Open( fileName, FileMode::Open ) );

                                               

                                                try

                                                {

                                                            // If the file is not empty, read the application settings.

                                                            // Read 4 bytes into a buffer to determine if the file is empty.

                                                            array<Byte>^testArray = gcnew array<Byte>(3);

                                                            int count = binReader->Read(testArray, 0, 3);

                                                           

                                                            Console::WriteLine("If file not empty, read the app...");

                                                            if ( count != -1 )

                                                            {

                                                                        aspectRatio = binReader->ReadSingle();

                                                                        lookupDir = binReader->ReadString();

                                                                        autoSaveTime = binReader->ReadInt32();

                                                                        showStatusBar = binReader->ReadBoolean();

                                                                        return;

                                                            }

                                                }

 

                                                // 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.

                        void Close()

                        {

                                    BinaryWriter^ binWriter = gcnew BinaryWriter( File::Open( fileName, FileMode::Create ) );

                                    Console::WriteLine("Create a file and store the app settings...");

 

                                    try

                                    {

                                                binWriter->Write( aspectRatio );

                                                binWriter->Write( lookupDir );

                                                binWriter->Write( autoSaveTime );

                                                binWriter->Write( showStatusBar );

                                    }

                                    finally

                                    {

                                                binWriter->Close();

                                    }

                        }

};

 

int main(array<System::String ^> ^args)

{

            // Load application settings.

            AppSettings^ appSettings = gcnew AppSettings;

            array<Object^>^someObject = {appSettings->AspectRatio.ToString(),appSettings->LookupDir,appSettings->AutoSaveTime.ToString(),appSettings->ShowStatusBar.ToString()};

           

            Console::WriteLine("Loading app settings...");

            Console::WriteLine("\n====App settings====\nAspect Ratio: {0}\nLookup directory: {1}\nAuto save time: {2} minutes"

   "\nShow status bar: {3}\n", someObject );

           

            // Change the settings.

            Console::WriteLine("Changing the settings...");

            appSettings->AspectRatio = 1.250F;

            appSettings->LookupDir =  "C:\\Temp";

            appSettings->AutoSaveTime = 10;

            appSettings->ShowStatusBar = true;

           

            // Save the new settings.

            Console::WriteLine("Saving the new settings...");

            appSettings->Close();

    return 0;

}

 

Build and run the project. The following is an output example.

 

C++ BinaryReader and BinaryWriter Example - an output sample

 

C# BinaryReader and BinaryWriter Example

 

Create a new console application project and add the following code.

 

C# BinaryReader and BinaryWriter Example - console application new project creation

 

using System;

using System.IO;

using System.Security.Permissions;

 

namespace BinaryReaderBinaryWriterCS

{

    class Program

    {

        static void Main(string[] args)

        {

            // Load application settings.

            Console.WriteLine("Load, store & retrieve the application settings...");

            AppSettings appSettings = new AppSettings();

            Console.WriteLine();

            Console.WriteLine("====The 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()});

 

            Console.WriteLine("Change the application settings...");

            // Change the settings.

            appSettings.AspectRatio = 1.250F;

            appSettings.LookupDir = @"C:\Temp";

            appSettings.AutoSaveTime = 10;

            appSettings.ShowStatusBar = true;

 

            Console.WriteLine("Save the settings...");

            // 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;

 

            Console.WriteLine("Creating a default application settings...");

            if (File.Exists(fileName))

            {

                BinaryReader binReader = new BinaryReader(File.Open(fileName, FileMode.Open));

                try

                {

                    // If the file is not empty, read the application settings. Read 4 bytes into a buffer to

                    // determine if the file is empty.

                    byte[ ] testArray = new byte[3];

                    int count = binReader.Read(testArray, 0, 3);

 

                    if (count != 0)

                    {

                        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()

        {

            Console.WriteLine("Creating a file and store the application settings...");

            using (BinaryWriter binWriter = new BinaryWriter(File.Open(fileName, FileMode.Create)))

            {

                binWriter.Write(aspectRatio);

                binWriter.Write(lookupDir);

                binWriter.Write(autoSaveTime);

                binWriter.Write(showStatusBar);

            }

        }

    }

}

 

An output sample:

 

C# BinaryReader and BinaryWriter Example - a sample of output in console mode  

 

VB .NET BinaryReader and BinaryWriter Example

 

Create a new empty project and you can use the solution and project name as shown in the following Figure.

 

VB .NET BinaryReader and BinaryWriter Example - an empty new project creation

 

Add a new class to the project as shown below.

 

VB .NET BinaryReader and BinaryWriter Example - adding a class to existing project

 

Add the following code.

 

Imports Microsoft.VisualBasic

Imports System

Imports System.IO

Imports System.Security.Permissions

 

Public Class Test

    Shared Sub Main()

 

        ' Load application settings.

        Dim appSettings As New AppSettings()

 

        Console.WriteLine("Load, store & retrieve application settings")

        Console.WriteLine()

        Console.WriteLine("==App settings==" & vbCrLf & "Aspect " & _

            "Ratio: {0}, Lookup directory: {1}," & vbCrLf & "Auto " & _

            "save time: {2} minutes, Show status bar: {3}" & vbCrLf, _

            New Object(3) {appSettings.AspectRatio.ToString(), _

            appSettings.LookupDir, _

            appSettings.AutoSaveTime.ToString(), _

            appSettings.ShowStatusBar.ToString()})

 

        ' Change the settings.

        Console.WriteLine("Change application settings...")

        appSettings.AspectRatio = 1.25

        appSettings.LookupDir = "C:\Temp"

        appSettings.AutoSaveTime = 10

        appSettings.ShowStatusBar = True

 

        ' Save the new settings.

        appSettings.Close()

 

    End Sub

 

End Class

 

' Store and retrieve application settings.

Public Class AppSettings

 

    Const fileName As String = "VBAppSettings#@@#.dat"

    Dim aspRatio As Single

    Dim lkupDir As String

    Dim saveTime As Integer

    Dim statusBar As Boolean

 

    Property AspectRatio() As Single

        Get

            Return aspRatio

        End Get

        Set(ByVal value As Single)

            aspRatio = Value

        End Set

    End Property

 

    Property LookupDir() As String

        Get

            Return lkupDir

        End Get

        Set(ByVal value As String)

            lkupDir = Value

        End Set

    End Property

 

    Property AutoSaveTime() As Integer

        Get

            Return saveTime

        End Get

        Set(ByVal value As Integer)

            saveTime = Value

        End Set

    End Property

 

    Property ShowStatusBar() As Boolean

        Get

            Return statusBar

        End Get

        Set(ByVal value As Boolean)

            statusBar = Value

        End Set

    End Property

 

    Sub New()

 

        ' Create default application settings.

        aspRatio = 1.3333

        lkupDir = "C:\VBAppDirectory"

        saveTime = 30

        statusBar = False

 

        Console.WriteLine("Creating a default application settings...")

        If File.Exists(fileName) Then

            Dim binReader As New BinaryReader( _

                File.Open(fileName, FileMode.Open))

            Try

 

                ' If the file is not empty, read the application settings.

                ' Read 4 bytes into a buffer to determine if the file is empty.

                Dim testArray As Byte() = {0, 0, 0, 0}

                Dim count As Integer = binReader.Read(testArray, 0, 3)

 

                If count <> 0 Then

                    aspRatio = binReader.ReadSingle()

                    lkupDir = binReader.ReadString()

                    saveTime = binReader.ReadInt32()

                    statusBar = binReader.ReadBoolean()

                    Return

                End If

 

                ' 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 ex As EndOfStreamException

                Console.WriteLine("{0} caught and ignored. " & _

                    "Using default values.", ex.GetType().Name)

            Finally

                binReader.Close()

            End Try

        End If

    End Sub

 

    ' Create a file and store the application settings.

    Sub Close()

        Dim binWriter As New BinaryWriter(File.Open(fileName, FileMode.Create))

        Console.WriteLine("Create a file and store the application settings...")

        Try

            binWriter.Write(aspRatio)

            binWriter.Write(lkupDir)

            binWriter.Write(saveTime)

            binWriter.Write(statusBar)

        Finally

            binWriter.Close()

        End Try

    End Sub

End Class

 

Build the solution/project.

 

VB .NET BinaryReader and BinaryWriter Example - building a project

 

Run/debug the program.

 

VB .NET BinaryReader and BinaryWriter Example - Running/debugging the project

 

Or you can use the short cut button.

 

VB .NET BinaryReader and BinaryWriter Example - a short-cut button

 

An output sample (as seen in the Visual Studio IDE's Output window):

 

VB .NET BinaryReader and BinaryWriter Example - Output sample seen in the Output window

 

 

 


 

< StreamReader & StreamWriter Program Examples | Main | Chap 3: Threading & Asynchronous >