< StreamWriter and StreamReader Examples | Main | MemoryStream & NetworkStream Examples >

 


 

Chapter 2 Part 4:

Managed I/O - Streams, Readers, and Writers

 

 

What do we have in this chapter 2 part 4?

  1. VB .NET Program Example – Writing and Reading Text File – StreamWriter and StreamReader

  2. C++ Program Example: Writing and Reading Binary – BinaryWriter and BinaryReader

  3. C# Program Example: Writing and Reading Binary – BinaryWriter and BinaryReader

  4. VB .NET Program Example: Writing and Reading Binary – BinaryWriter and BinaryReader

 

 

 

VB .NET Example – Writing and Reading Text File – StreamWriter and StreamReader

 

Create a new console application project. You can use the solution and project name as shown in the following Figure.

 

VB .NET StreamWriter and StreamReader Console Mode application project using VS 2008

 

Add the following code.

 

Imports System

Imports System.IO

 

Module Module1

    'The main entry point for the application.

    Sub Main()

        Dim MyStreamWriter As StreamWriter = Nothing

 

        ' Let's write a string to a file named Jim.txt

        Try

            Try

                MyStreamWriter = New StreamWriter(".\\Jim.txt")

                Console.WriteLine("StreamWriter() is OK and ready for writing...")

            Catch e As Exception

                Throw New Exception("Failed to create a stream writer with error: " + e.Message)

            End Try

 

            Try

                Console.WriteLine("Writing some text into a file...")

                MyStreamWriter.WriteLine("Using stream writers is easy!")

                MyStreamWriter.WriteLine("Using stream readers is also easy!")

                MyStreamWriter.WriteLine("Yes it is true!")

            Catch e As Exception

                Throw New Exception("Failed to write using a stream writer with error: " + e.Message)

            End Try

            Console.WriteLine("Finished writing text to a file")

        Catch e As Exception

            Console.WriteLine(e.Message)

            Exit Sub

        Finally

            MyStreamWriter.Close()

            Console.WriteLine("Closing the StreamWriter()...")

        End Try

 

        Dim MyStreamReader As StreamReader = Nothing

 

        Try

            Try

                MyStreamReader = New StreamReader(".\\Jim.txt")

                Console.WriteLine("StreamReader() is OK and ready for reading...")

            Catch e As Exception

                Throw New Exception("Failed to open stream reader with error: " + e.Message)

            End Try

 

            Dim FileData As String = Nothing

 

            Console.WriteLine("Reading file content using ReadLine()")

            Do

                Try

                    FileData = MyStreamReader.ReadLine()

                Catch e As Exception

                    Throw New Exception("Failed to read from stream with error: " + e.Message)

                End Try

 

                If Not IsNothing(FileData) Then

                    Console.WriteLine("We read -> " + FileData)

                End If

 

            Loop While Not IsNothing(FileData)

            Console.WriteLine("Finished reading text from a file.")

        Catch e As Exception

            Console.WriteLine(e.Message)

            Exit Sub

        Finally

            MyStreamReader.Close()

            Console.WriteLine("Closing the StreamReader()...")

        End Try

    End Sub

End Module

 

An output sample:

 

VB .NET StreamWriter and StreamReader Console Mode application project using VS 2008 - output example

 

You can try opening the generated file as shown below.

 

VB .NET StreamWriter and StreamReader Console Mode application project using VS 2008 - the generated text file

 

C++ Example: Writing and Reading Binary – BinaryWriter and BinaryReader

 

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

 

C++/CLI BinaryWriter and BinaryReader CLR console application project example

 

Add the following code.

 

// BinaryIOCP.cpp : main project file.

 

#include "stdafx.h"

 

using namespace System;

using namespace System::IO;

 

[STAThread]

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

{

    FileStream^ MyFileStream = nullptr;

 

            try

            {

                String^ FileName = "C:\\Temp\\crappy.dat";

                try

                {

                     MyFileStream = gcnew FileStream(FileName, FileMode::Create, FileAccess::ReadWrite);

                     Console::WriteLine("{0} file created/opened successfully...", FileName);

                }

                catch (Exception^ e)

                {

                    throw gcnew Exception("Failed to create/open filestream with error: " + e->Message);

                }

 

                BinaryWriter^ MyBinaryWriter = nullptr;

 

                try

                {

                    MyBinaryWriter = gcnew BinaryWriter(MyFileStream);

                    Console::WriteLine("Instantiate BinaryWriter object is OK...");

                }

                catch (Exception^ e)

                {

                    throw gcnew Exception("Failed to create binary writer with error: " + e->Message);

                }

 

                // Now let's write 4 integers to a file.

                try

                {

                    Console::WriteLine("Writing 4 integers using binary writer...");

                    MyBinaryWriter->Write(456);

                    MyBinaryWriter->Write(457);

                    MyBinaryWriter->Write(458);

                    MyBinaryWriter->Write(459);

                    MyBinaryWriter->Flush();

                }

                catch (Exception^ e)

                {

                    throw gcnew Exception("Write failed with error: " + e->Message);

                }

 

                // Now let's prepare to read the integers that we have just written. To

                // do so requires seeking back to the beginning of the file and reading the bytes.

                Console::WriteLine();

                try

                {

                   MyFileStream->Seek(0, SeekOrigin::Begin);

                   Console::WriteLine("Seek() is OK...");

                }

                catch (Exception^ e)

                {

                    throw gcnew Exception("Seek() failed with error: " + e->Message);

                }

 

                BinaryReader^ MyBinaryReader = nullptr;

 

                try

                {

                    MyBinaryReader = gcnew BinaryReader(MyFileStream);

                    Console::WriteLine("Instantiate new BinaryReader object is OK...");

                }

                catch (Exception^ e)

                {

                    throw gcnew Exception("Failed to create binary reader with error "  + e->Message);

                }

                     Console::WriteLine("Reading binary using ReadInt32()...");

 

                while (true)

                {

                    int Number;

 

                    try

                    {

                         Number = MyBinaryReader->ReadInt32();

                         Console::WriteLine("We read number -> " + Number.ToString());

                    }

                    catch (EndOfStreamException^)

                    {

                        break;

                    }

                    catch (Exception^ e)

                    {

                        throw gcnew Exception("Failed to read using binary reader with error: " + e->Message);

                    }

                }

            }

            catch (Exception^ e)

            {

               Console::WriteLine(e->Message);

            }

            finally

            {

                Console::WriteLine("Closing FileStream...");

                MyFileStream->Close();

            }

    return 0;

}

 

Build and run the project. The following is the output example when run at the Windows console/command prompt.

 

  C++/CLI BinaryWriter and BinaryReader CLR console application project example - a sample console output

 

 

C# Example: Writing and Reading Binary – BinaryWriter and BinaryReader

 

Create a new console application project. You can use the solution and project name as shown in the following Figure.

 

C# BinaryWriter and BinaryReader console mode application project example

 

Add the following code.

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

 

// <summary>

// This sample demonstrates how to use the binary stream readers and

// writers to write and read integers to a file.

// </summary>

namespace BinaryIOCS

{

    class Program

    {   // <summary>

        // The main entry point for the application.

        // </summary>

        [STAThread]

        static void Main(string[ ] args)

        {

            FileStream MyFileStream = null;

 

            try

            {

                try

                {

                    MyFileStream = new FileStream(".\\Jim.dat", FileMode.Create, FileAccess.ReadWrite);

                    Console.WriteLine("Jim.dat file created/opened successfully");

                }

                catch (Exception e)

                {

                    throw new Exception("Failed to create/open filestream with error: " + e.Message);

                }

 

                BinaryWriter MyBinaryWriter = null;

 

                try

                {

                    MyBinaryWriter = new BinaryWriter(MyFileStream);

                    Console.WriteLine("Instantiate BinaryWriter object...");

 

                }

                catch (Exception e)

                {

                    throw new Exception("Failed to create binary writer with error: " + e.Message);

                }

 

                // Now let's write 4 integers to a file.

                try

                {

                    Console.WriteLine("Writing 4 integers using Write()...");

                    MyBinaryWriter.Write(456);

                    MyBinaryWriter.Write(457);

                    MyBinaryWriter.Write(458);

                    MyBinaryWriter.Write(459);

                    MyBinaryWriter.Flush();

                }

                catch (Exception e)

                {

                    throw new Exception("Write failed with error: " + e.Message);

                }

 

                // Now let's prepare to read the integers that we have just written. To

                // do so requires seeking back to the beginning of the file and reading the bytes.

                Console.WriteLine();

                try

                {

                    MyFileStream.Seek(0, SeekOrigin.Begin);

                    Console.WriteLine("Seek() is OK...");

                }

                catch (Exception e)

                {

                    throw new Exception("Seek failed with error: " + e.Message);

                }

                BinaryReader MyBinaryReader = null;

 

                try

                {

                    MyBinaryReader = new BinaryReader(MyFileStream);

                    Console.WriteLine("Instantiate new BinaryReader object...");

                }

                catch (Exception e)

                {

                    throw new Exception("Failed to create binary reader with error "  + e.Message);

                }

                Console.WriteLine("Reading binary using ReadInt32()...");

                while (true)

                {

                    int Number;

 

                    try

                    {

                        Number = MyBinaryReader.ReadInt32();

                        Console.WriteLine("We read number -> " + Number.ToString());

                    }

                    catch (EndOfStreamException)

                    {

                        break;

                    }

                    catch (Exception e)

                    {

                        throw new Exception("Failed to read using binary reader with error: " + e.Message);

                    }

                }

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

            finally

            {

                MyFileStream.Close();

                Console.WriteLine("Closing FileStream...");

            }

        }

    }

}

 

An output sample:

 

C# BinaryWriter and BinaryReader console mode application project example - output example

 

VB .NET Example: Writing and Reading Binary – BinaryWriter and BinaryReader

 

Create a new console application project. You can use the solution and project name as shown in the following Figure.

 

VB .NET BinaryWriter and BinaryReader console mode application project example

 

Add the following code.

 

Imports System

Imports System.IO

 

' This sample demonstrates how to use the binary stream readers and

' writers to write and read integers to a file.

Module Module1

    ' The main entry point for the application.

    Sub Main()

        Dim MyFileStream As FileStream = Nothing

 

        Try

            Try

                MyFileStream = New FileStream(".\\Jim.dat", FileMode.Create, FileAccess.ReadWrite)

                Console.WriteLine("Jim.dat file created/opened successfully")

            Catch e As Exception

                Throw New Exception("Failed to create/open filestream with error: " + e.Message)

            End Try

 

            Dim MyBinaryWriter As BinaryWriter = Nothing

 

            Try

                Console.WriteLine("Instantiate BinaryWriter object for writing a binary...")

                MyBinaryWriter = New BinaryWriter(MyFileStream)

            Catch e As Exception

                Throw New Exception("Failed to create binary writer with error: " + e.Message)

            End Try

 

            ' Now let's write 4 integers to a file.

            Console.WriteLine("Writing 4 integers...")

            Try

                MyBinaryWriter.Write(456)

                MyBinaryWriter.Write(457)

                MyBinaryWriter.Write(458)

                MyBinaryWriter.Write(459)

                MyBinaryWriter.Flush()

            Catch e As Exception

                Throw New Exception("Write failed with error: " + e.Message)

            End Try

 

            ' Now let's prepare to read the integers that we have just written. To

            ' do so requires seeking back to the beginning of the file and reading the bytes.

            Console.WriteLine()

            Try

                MyFileStream.Seek(0, SeekOrigin.Begin)

                Console.WriteLine("Seek() is OK...")

            Catch e As Exception

                Throw New Exception("Seek failed with error: " + e.Message)

            End Try

 

            Dim MyBinaryReader As BinaryReader = Nothing

 

            Try

                Console.WriteLine("Instantiate BinaryReader object for reading a binary...")

                MyBinaryReader = New BinaryReader(MyFileStream)

            Catch e As Exception

                Throw New Exception("Failed to create binary reader with error " + e.Message)

            End Try

 

            Do While True

                Dim Number As Integer

                Try

                    Console.WriteLine("Reading using ReadInt32()...")

                    Number = MyBinaryReader.ReadInt32()

                    Console.WriteLine("We read number -> " + Number.ToString())

                Catch e As EndOfStreamException

                    Exit Do

                Catch e As Exception

                    Throw New Exception("Failed to read using binary reader with error: " + e.Message)

                End Try

            Loop

        Catch e As Exception

            Console.WriteLine(e.Message)

        Finally

            Console.WriteLine("Closing a FileStream...")

            MyFileStream.Close()

        End Try

    End Sub

End Module

 

An output sample:

 

VB .NET BinaryWriter and BinaryReader console mode application project example - output example

 

 

 


 

< StreamWriter and StreamReader Examples | Main | MemoryStream & NetworkStream Examples >