C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

Introduction To C# Streams

Streams in C# are an essential part of the System.IO namespace and provide a generic way to read and write data to various sources, such as files, memory, and network. This tutorial will cover the following topics related to streams in C#:

  • Stream overview
  • Reading data from a stream
  • Writing data to a stream
  • Closing a stream

Let's begin!

  • Stream overview

The Stream class is an abstract base class that represents a generic view of a sequence of bytes. There are several classes derived from the Stream class that handle specific data sources, such as:

  • FileStream: Reading and writing data to files
  • MemoryStream: Reading and writing data to memory
  • NetworkStream: Reading and writing data to network sockets
  • Reading data from a stream

To read data from a stream, you can use the Read method, which reads a specified number of bytes from the stream into a byte array. Here's an example of reading data from a FileStream:

using System.IO;

string filePath = "path/to/your/file.txt";
byte[] buffer = new byte[1024];

using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
    int bytesRead;
    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        // Process the data in the buffer
    }
}

In this example, we read data from a file in chunks of 1024 bytes until we reach the end of the file. The Read method returns the number of bytes actually read, or 0 if the end of the stream is reached.

  • Writing data to a stream

To write data to a stream, you can use the Write method, which writes a specified number of bytes from a byte array to the stream. Here's an example of writing data to a FileStream:

using System.IO;
using System.Text;

string filePath = "path/to/your/file.txt";
byte[] data = Encoding.UTF8.GetBytes("Hello, World!");

using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
    fileStream.Write(data, 0, data.Length);
}

In this example, we write a string to a file as UTF-8 encoded bytes. The Write method writes the specified number of bytes from the byte array to the stream.

  • Closing a stream

It is important to close a stream after you finish using it to release the resources associated with it. If you use the using statement, the stream will be closed automatically when the block is exited:

using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
    // Your code to read or write data
}

If you don't use the using statement, you should call the Close method explicitly:

FileStream fileStream = new FileStream(filePath, FileMode.Open);
// Your code to read or write data
fileStream.Close();

That's it! You've now learned about streams in C#, including an overview of the Stream class and its derived classes, reading data from a stream, writing data to a stream, and closing a stream. Streams provide a flexible and efficient way to handle input and output operations in various scenarios, such as working with files, memory, or network data.

  1. How to use streams in C#

    Streams in C# provide a generic way to work with input and output data.

    using System;
    using System.IO;
    
    class Program
    {
        static void Main()
        {
            using (FileStream fileStream = new FileStream("example.txt", FileMode.Open))
            {
                // Use fileStream for reading or writing
            }
        }
    }
    
  2. Reading and writing with streams in C#

    Streams support both reading and writing operations.

    using (FileStream fileStream = new FileStream("example.txt", FileMode.Create))
    {
        // Writing to the file
        byte[] data = Encoding.UTF8.GetBytes("Hello, Stream!");
        fileStream.Write(data, 0, data.Length);
    
        // Reading from the file
        fileStream.Seek(0, SeekOrigin.Begin);
        byte[] buffer = new byte[1024];
        int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
        string content = Encoding.UTF8.GetString(buffer, 0, bytesRead);
        Console.WriteLine(content);
    }
    
  3. Working with MemoryStream in C#

    MemoryStream allows reading and writing to an in-memory buffer.

    using (MemoryStream memoryStream = new MemoryStream())
    {
        // Use memoryStream for in-memory operations
    }
    
  4. Binary data and streams in C#

    Streams support binary data handling for scenarios like reading or writing images.

    using (FileStream fileStream = new FileStream("image.jpg", FileMode.Open))
    {
        // Process binary data from the file
    }
    
  5. Text data and streams in C#

    StreamReader and StreamWriter are useful for working with text data.

    using (StreamReader reader = new StreamReader("textfile.txt"))
    {
        string line = reader.ReadLine();
    }
    
  6. C# stream handling for network communication

    NetworkStream is used for communication over network sockets.

    using (TcpClient client = new TcpClient("localhost", 8080))
    using (NetworkStream networkStream = client.GetStream())
    {
        // Use networkStream for communication
    }
    
  7. Using BufferedStream in C#

    BufferedStream improves I/O performance by buffering data.

    using (FileStream fileStream = new FileStream("largefile.txt", FileMode.Open))
    using (BufferedStream bufferedStream = new BufferedStream(fileStream))
    {
        // Use bufferedStream for improved performance
    }
    
  8. Seeking and positioning in streams in C#

    Seek and Position allow navigating within streams.

    fileStream.Seek(0, SeekOrigin.Begin);
    long currentPosition = fileStream.Position;
    
  9. Stream encoding and decoding in C#

    Encoding classes facilitate converting between byte arrays and strings.

    byte[] data = Encoding.UTF8.GetBytes("Hello, Encoding!");
    string text = Encoding.UTF8.GetString(data);
    
  10. Combining streams in C#

    Streams can be combined using classes like CryptoStream for cryptographic operations.

    using (CryptoStream cryptoStream = new CryptoStream(fileStream, cryptoTransform, CryptoStreamMode.Read))
    {
        // Use cryptoStream for secure operations
    }