BufferedStream, MemoryStream and CharacterStream Class in C#

Introduction

This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.

What is BufferedStream Class?

The BufferedStream class also extends the Stream class. Buffers, or cached blocks of data in memory, provide speed and stability to the process of reading or writing because they prevent numerous calls to the operating system. Buffered streams are used in conjunction with other streams to provide better read/write performance. The BufferedStream class can be used to either read data or write data but it cannot be used to perform both read and write operations together. The class has been optimized so that it maintains a suitable buffer at all times. When a buffer is not required, instead of slowing down the process, the class does not allocate any space in memory. File streams are already buffered and therefore a buffered stream is generally used to buffer network streams used in networking applications.

What is MemoryStream Class?

A memory stream is created from an array of unsigned bytes rather than from a file or other stream. Memory streams are used as temporary, in-memory storage (temporary buffers) in lieu of creating temporary files. This stream is highly optimized for speed since the data is stored in memory and the processor can easily access it. Memory streams should be used to store frequently accessed data.

The Read and Write methods of the MemoryStream class read and write from an internal buffer that is created when the memory stream is created. The example shown in Listing 6.9 uses the MemoryStream class to add a custom signature at the end of the specified file.

MemoryStream Reading and Writing Example

using System;
using System.IO;
using System.Text;

public class MemStream
{
    public static void Main(string[] args)
    {
        // Check the number of arguments
        if (args.Length < 1)
        {
            Console.WriteLine("Usage: MemStream <sourcefile>");
            return;
        }

        try
        {
            // Get the current date
            DateTime dt = DateTime.Now;
            string tag = "This file was signed on " + dt.ToShortDateString();

            // Get a byte array from the string
            byte[] tagarray = System.Text.Encoding.ASCII.GetBytes(tag.ToCharArray());

            // Construct a memory stream with the byte array as a parameter
            MemoryStream mstream = new MemoryStream(tagarray);

            // Open a FileStream on the source file
            FileStream fout = new FileStream(args[0], FileMode.Open, FileAccess.Write);

            // Seek to the end of the file
            fout.Seek(0, SeekOrigin.End);
            Byte[] buffer = new Byte[tagarray.Length];
            Console.WriteLine("Starting to write signature");

            // Read the contents of the MemoryStream into a buffer
            int n = mstream.Read(buffer, 0, buffer.Length);

            // Write the buffer to the file
            fout.Write(buffer, 0, n);

            // Close the streams
            mstream.Close();
            fout.Close();
            Console.WriteLine("Signature Written");
        }
        catch (IOException e)
        {
            Console.WriteLine("An IO Exception Occurred :" + e);
        }
        catch (Exception oe)
        {
            Console.WriteLine("An Exception Occurred :" + oe);
        }

        Console.ReadLine();
    }
}

In this example, a MemoryStream object is created and a byte array–containing signature is stored in the memory stream's buffer. Then a file stream is opened on the source file and the Seek method is used to seek to the end of the file. Once positioned at the end of the file, the code gets the contents of the memory stream and writes the contents to the file stream.

What is Character Streams?

Character streams treat data as a stream of characters. These streams are most useful if they contain data in a format readable by humans.

Conclusion

Hope this article would have helped you in understanding BufferedStream, MemoryStream and CharacterStream Class in C#. See other articles on the website on .NET and C#.


Similar Articles