< NegotiateStream Class Client Example | Main | StreamReader & StreamWriter Program Examples >

 


 

Chapter 2 Part 14:

Managed I/O - Streams, Readers, and Writers

 

 

What do we have in this chapter 2 Part 14?

  1. AuthenticatedStream Class

  2. Readers and Writers

  3. StreamReader and StreamWriter

  4. C++ StreamWriter and StreamReader Program Example

  5. C# StreamWriter and StreamReader Program Example

  6. VB .NET StreamWriter and StreamReader Program Example

 

 

 

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

 

AuthenticatedStream Class

 

This class provides methods for passing credentials across a stream and requesting or performing authentication for client-server applications. This abstract class provides methods and properties that are common to authenticated streams.

Authenticated streams can provide authentication, data signing, and encryption services that can help maintain the integrity and confidentiality of data transmitted using the InnerStream.

The security protocol implemented by a class that derives from AuthenticatedStream together with the security protocols supported on the client and server will determine the security features that are available to an application. The NegotiateStream and SslStream classes inherit from AuthenticatedStream and implement the Negotiate and Secure Sockets Layer security protocols, respectively.

Notes to Inheritors: The following members must be overridden in a derived class: IsAuthenticated, IsEncrypted, IsMutuallyAuthenticated, IsServer, and IsSigned.

 

C#

 

// The following class displays the properties of an authenticatedStream.

public class AuthenticatedStreamReporter

{

    public static void DisplayProperties(AuthenticatedStream stream)

    {

        Console.WriteLine("IsAuthenticated: {0}", stream.IsAuthenticated);

        Console.WriteLine("IsMutuallyAuthenticated: {0}", stream.IsMutuallyAuthenticated);

        Console.WriteLine("IsEncrypted: {0}", stream.IsEncrypted);

        Console.WriteLine("IsSigned: {0}", stream.IsSigned);

        Console.WriteLine("IsServer: {0}", stream.IsServer);

    }

}

 

Readers and Writers

 

Stream readers and writers provide a convenient way to read and write text and binary data types to streams. You might have noticed in our discussions so far that stream Read() and Write() methods perform I/O using byte-type data arrays. Using byte-type arrays to read and write data makes stream classes inconvenient, especially when you’re writing text because your application has to spend a great deal of time converting data types to byte arrays. There are two reader classes, StreamReader and BinaryReader, and two writer classes, StreamWriter and BinaryWriter, that make handling I/O on streams a snap.

 

StreamReader and StreamWriter

 

The best way to read and write character-based data to a stream is by using the StreamReader and StreamWriter classes. Both classes are based on the abstract classes TextReader and TextWriter that enable you to read and write a sequence of characters. These classes also allow you to read and write characters in different character encoding formats, such as ASCII or Universal Character Set (UCS). Many UCS Transformation Formats (UTF) are available, such as an 8-bit encoding form called UTF-8. Table 2-4 describes the available encoding techniques supported by the StreamReader and StreamWriter classes. By default, these reader/ writer classes use UTF-8 encoding and decoding. However, you can specify other techniques through one of the constructor methods.

 

Table 2-4: Encoding/Decoding Techniques for Stream Readers/Writers

 

Technique

Description

ASCII

Unicode characters are encoded/decoded as 7-bit ASCII characters.

Big-endian Unicode

Unicode characters are encoded/decoded in big-endian byte form.

Unicode

Unicode characters are encoded/decoded as UTF-16 characters.

UTF-7

Unicode characters are encoded/decoded as UTF-7 characters.

UTF-8

Unicode characters are encoded/decoded as UTF-8 characters.

 

The most useful methods in the StreamWriter class are Write() and WriteLine(), which come from the TextWriter class. The only difference between the two methods is that WriteLine() places a carriage return followed by a line feed at the end of the text and Write() does not. Both methods have many prototypes and allow you to read and write many numerical data types and strings as text to a stream. For example, the following code fragment shows how to write a simple character string to a file stream:

 

C#

 

StreamWriter MyStreamWriter = new StreamWriter(MyFileStream);

MyStreamWriter.WriteLine("Using stream writers is great!");

 

Visual Basic .NET

 

Dim MyStreamWriter As StreamWriter

MyStreamWriter = New StreamWriter(MyFileStream)

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

 

In the StreamReader class, there’s a Read() method that allows you to read a single character or a specified number of characters from a stream. There’s also a ReadLine() method that allows you to read a line of text into a string. Finally, there’s a ReadToEnd() method that will read the entire contents of the stream and return a string. ReadToEnd() is great for downloading a small text file over a network stream.

 

C++ StreamWriter and StreamReader Example

 

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

 

C++ StreamWriter and StreamReader Example - a new CLR console application project creation

 

Add the following code.

 

// StreamWriterCP.cpp : main project file.

 

#include "stdafx.h"

 

using namespace System;

using namespace System::IO;

using namespace System::Text;

 

static void CreateTextFile(String^ fileName, String^ textToAdd)

{

    // The Log file...

    String^ logFile = DateTime::Now.ToShortDateString()->Replace("/", "-")->Replace("\\", "-") + ".log";

 

    try

    {

    StreamWriter^ swFromFile = gcnew StreamWriter(logFile);

    Console::WriteLine(L"Write(), {0} file...", logFile);

    swFromFile->Write(textToAdd);

    Console::WriteLine(L"Flush()");

    swFromFile->Flush();

    Console::WriteLine(L"Close()");

    swFromFile->Close();

    Console::WriteLine();

 

    // file name from Main()

    FileStream^ fs = gcnew FileStream(fileName, FileMode::CreateNew, FileAccess::Write, FileShare::None);

    StreamWriter^ swFromFileStream = gcnew StreamWriter(fs);

    Console::WriteLine(L"Write(), {0} file...", fileName);

    swFromFileStream->Write(textToAdd);

    Console::WriteLine(L"Flush()");

    swFromFileStream->Flush();

    Console::WriteLine(L"Close()");

    swFromFileStream->Close();

    Console::WriteLine();

 

    // New file

    fileName = L"text2.txt";

    FileStream^ fs1 = gcnew FileStream(fileName, FileMode::CreateNew, FileAccess::Write, FileShare::None);

 

    StreamWriter^ swFromFileStreamDefaultEnc = gcnew StreamWriter(fs1, Encoding::Default);

    Console::WriteLine(L"Write(), {0} file...", fileName);

    swFromFileStreamDefaultEnc->Write(textToAdd);

    Console::WriteLine(L"Flush()");

    swFromFileStreamDefaultEnc->Flush();

    Console::WriteLine(L"Close()");

    swFromFileStreamDefaultEnc->Close();

    Console::WriteLine();

 

    StreamWriter^ swFromFileTrue = gcnew StreamWriter(fileName, true);

    Console::WriteLine(L"Write(), {0} file...", fileName);

    swFromFileTrue->Write(textToAdd);

    Console::WriteLine(L"Flush()");

    swFromFileTrue->Flush();

    Console::WriteLine(L"Close()");

    swFromFileTrue->Close();

    Console::WriteLine();

 

    StreamWriter^ swFromFileTrueUTF8Buffer = gcnew StreamWriter(fileName, true, Encoding::UTF8, 512);

    Console::WriteLine(L"Write(), {0} file...", fileName);

    swFromFileTrueUTF8Buffer->Write(textToAdd);

    Console::WriteLine(L"Flush()");

    swFromFileTrueUTF8Buffer->Flush();

    Console::WriteLine(L"Close()");

    swFromFileTrueUTF8Buffer->Close();

    Console::WriteLine();

 

    StreamWriter^ swFromFileTrueUTF8 = gcnew StreamWriter(fileName, true, Encoding::UTF8);

    Console::WriteLine(L"Write(), {0} file...", fileName);

    swFromFileTrueUTF8->Write(textToAdd);

    Console::WriteLine(L"Flush()");

    swFromFileTrueUTF8->Flush();

    Console::WriteLine(L"Close()");

    swFromFileTrueUTF8->Close();

    Console::WriteLine();

 

    // New file

    fileName = L"text3.txt";

    FileStream^ fs2 = gcnew FileStream(fileName, FileMode::CreateNew, FileAccess::Write, FileShare::None);

 

    StreamWriter^ swFromFileStreamUTF8Buffer = gcnew StreamWriter(fs2, Encoding::UTF8, 512);

    Console::WriteLine(L"Write(), {0} file...", fileName);

    swFromFileStreamUTF8Buffer->Write(textToAdd);

    Console::WriteLine(L"Flush()");

    swFromFileStreamUTF8Buffer->Flush();

    Console::WriteLine(L"Close()");

    swFromFileStreamUTF8Buffer->Close();

    }

    catch(Exception^ err)

    {

          Console::WriteLine(L"Bastard error: " + err->Message);

     }

}

 

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

{

    String^ fileName = L"testo.txt";

    String^ textToAdd = L"Just a line of test text..";

    CreateTextFile(fileName, textToAdd);

    return 0;

}

 

 

 

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

 

C++ StreamWriter and StreamReader Example - a sample output

 

The files created are shown below.

 

 

 

C# StreamWriter and StreamReader Example

 

Example: The following code example demonstrates the StreamWriter constructors. Create a new console application project. You can use the solution and project name as used in the following program, StreamWriterCS.

 

using System;

using System.IO;

 

namespace StreamWriterCS

{

    public class Program

    {

        public static void CreateTextFile(string fileName, string textToAdd)

        {

            // Log file...

            string logFile = DateTime.Now.ToShortDateString().Replace(@"/", @"-").Replace(@"\", @"-") + ".log";

 

            StreamWriter swFromFile = new StreamWriter(logFile);

            Console.WriteLine("Write(), {0} file...", logFile);

            swFromFile.Write(textToAdd);

            Console.WriteLine("Flush()");

            swFromFile.Flush();

            Console.WriteLine("Close()");

            swFromFile.Close();

            Console.WriteLine("");

 

            // file name from Main()

            FileStream fs = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write, FileShare.None);

 

            StreamWriter swFromFileStream = new StreamWriter(fs);

            Console.WriteLine("Write(), {0} file...", fileName);

            swFromFileStream.Write(textToAdd);

            Console.WriteLine("Flush()");

            swFromFileStream.Flush();

            Console.WriteLine("Close()");

            swFromFileStream.Close();

            Console.WriteLine("");

 

            // New file

            fileName = "text2.txt";

            FileStream fs1 = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write, FileShare.None);

            StreamWriter swFromFileStreamDefaultEnc = new System.IO.StreamWriter(fs1, System.Text.Encoding.Default);

            Console.WriteLine("Write(), {0} file...", fileName);

            swFromFileStreamDefaultEnc.Write(textToAdd);

            Console.WriteLine("Flush()");

            swFromFileStreamDefaultEnc.Flush();

            Console.WriteLine("Close()");

            swFromFileStreamDefaultEnc.Close();

            Console.WriteLine("");

 

            StreamWriter swFromFileTrue = new StreamWriter(fileName, true);

            Console.WriteLine("Write(), {0} file...", fileName);

            swFromFileTrue.Write(textToAdd);

            Console.WriteLine("Flush()");

            swFromFileTrue.Flush();

            Console.WriteLine("Close()");

            swFromFileTrue.Close();

            Console.WriteLine("");

 

            StreamWriter swFromFileTrueUTF8Buffer = new StreamWriter(fileName, true, System.Text.Encoding.UTF8, 512);

            Console.WriteLine("Write(), {0} file...", fileName);

            swFromFileTrueUTF8Buffer.Write(textToAdd);

            Console.WriteLine("Flush()");

            swFromFileTrueUTF8Buffer.Flush();

            Console.WriteLine("Close()");

            swFromFileTrueUTF8Buffer.Close();

            Console.WriteLine("");

 

            StreamWriter swFromFileTrueUTF8 = new StreamWriter(fileName, true, System.Text.Encoding.UTF8);

            Console.WriteLine("Write(), {0} file...", fileName);

            swFromFileTrueUTF8.Write(textToAdd);

            Console.WriteLine("Flush()");

            swFromFileTrueUTF8.Flush();

            Console.WriteLine("Close()");

            swFromFileTrueUTF8.Close();

            Console.WriteLine("");

 

            // New file

            fileName = "text3.txt";

            FileStream fs2 = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write, FileShare.None);

 

            StreamWriter swFromFileStreamUTF8Buffer = new StreamWriter(fs2, System.Text.Encoding.UTF8, 512);

            Console.WriteLine("Write(), {0} file...", fileName);

            swFromFileStreamUTF8Buffer.Write(textToAdd);

            Console.WriteLine("Flush()");

            swFromFileStreamUTF8Buffer.Flush();

            Console.WriteLine("Close()");

            swFromFileStreamUTF8Buffer.Close();

        }

 

        public static int Main(string[] args)

        {

            string fileName = "test.txt";

            string textToAdd = "A line of test text..";

            CreateTextFile(fileName, textToAdd);

            return 0;

        }

    }

}

 

An output sample:

 

 

The created files can be seen under the current folder (Debug folder).

 

 

Check the files content.

 

VB .NET StreamWriter and StreamReader Example

 

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

 

Imports System

Imports System.IO

 

Module Module1

    Public Sub CreateTextFile(ByVal FileName As String, ByVal TextToAdd As String)

 

        Dim SwFromFile As StreamWriter = New StreamWriter(FileName)

        Console.WriteLine("Write(), " + FileName)

        SwFromFile.Write(TextToAdd)

        Console.WriteLine("Flush(), ...")

        SwFromFile.Flush()

        Console.WriteLine("Close()")

        SwFromFile.Close()

        Console.WriteLine()

 

        Dim FileName0 As String = "test0.txt"

        Dim Fs0 As FileStream = New FileStream(FileName0, FileMode.CreateNew, FileAccess.Write, FileShare.None)

        Dim SwFromFileStream As StreamWriter = New StreamWriter(Fs0)

 

        Console.WriteLine("Write(), " + FileName0)

        SwFromFileStream.Write(TextToAdd)

        Console.WriteLine("Flush(), ...")

        SwFromFileStream.Flush()

        Console.WriteLine("Close()")

        SwFromFileStream.Close()

        Console.WriteLine()

 

        Dim FileName1 As String = "test1.txt"

        Dim Fs1 As FileStream = New FileStream(FileName1, FileMode.CreateNew, FileAccess.Write, FileShare.None)

        Dim SwFromFileStreamDefaultEnc As StreamWriter = New StreamWriter(Fs1, System.Text.Encoding.Default)

 

        Console.WriteLine("Write(), " + FileName1)

        SwFromFileStreamDefaultEnc.Write(TextToAdd)

        Console.WriteLine("Flush(), ...")

        SwFromFileStreamDefaultEnc.Flush()

        Console.WriteLine("Close()")

        SwFromFileStreamDefaultEnc.Close()

        Console.WriteLine()

 

        Dim SwFromFileTrue As StreamWriter = New StreamWriter(FileName1, True)

        Console.WriteLine("Write(), " + FileName1)

        SwFromFileTrue.Write(TextToAdd)

        Console.WriteLine("Flush(), ...")

        SwFromFileTrue.Flush()

        Console.WriteLine("Close()")

        SwFromFileTrue.Close()

        Console.WriteLine()

 

        Dim SwFromFileTrueUTF8Buffer = New StreamWriter(FileName1, True, System.Text.Encoding.UTF8, 512)

        Console.WriteLine("Write(), " + FileName1)

        SwFromFileTrueUTF8Buffer.Write(TextToAdd)

        Console.WriteLine("Flush(), ...")

        SwFromFileTrueUTF8Buffer.Flush()

        Console.WriteLine("Close()")

        SwFromFileTrueUTF8Buffer.Close()

        Console.WriteLine()

 

        Dim SwFromFileTrueUTF8 = New StreamWriter(FileName1, True, System.Text.Encoding.UTF8)

        Console.WriteLine("Write(), " + FileName1)

        SwFromFileTrueUTF8.Write(TextToAdd)

        Console.WriteLine("Flush(), ...")

        SwFromFileTrueUTF8.Flush()

        Console.WriteLine("Close()")

        SwFromFileTrueUTF8.Close()

        Console.WriteLine()

 

        Dim FileName2 As String = "test2.txt"

        Dim Fs2 As FileStream = New FileStream(FileName2, FileMode.CreateNew, FileAccess.Write, FileShare.None)

        Dim SwFromFileStreamUTF8Buffer = New StreamWriter(Fs2, System.Text.Encoding.UTF8, 512)

 

        Console.WriteLine("Write(), " + FileName2)

        SwFromFileStreamUTF8Buffer.Write(TextToAdd)

        Console.WriteLine("Flush(), ...")

        SwFromFileStreamUTF8Buffer.Flush()

        Console.WriteLine("Close()")

        SwFromFileStreamUTF8Buffer.Close()

    End Sub

 

    Sub Main()

        Dim FileName As String

        FileName = "test.txt"

        Dim TextToAdd As String = "A simple line of text..."

        Call CreateTextFile(FileName, TextToAdd)

    End Sub

End Module

 

An output sample:

 

VB .NET StreamWriter and StreamReader Example - an output sample in action

 

The following code example uses a StreamReader object to read text from a file. This is a console mode application.

 

 

 


 

< NegotiateStream Class Client Example | Main | StreamReader & StreamWriter Program Examples >