Comporre flussi

Un archivio di backup è un supporto di archiviazione, ad esempio un disco o la memoria. Ogni tipo di archivio di backup implementa il flusso come implementazione della classe Stream.

Ogni tipo di flusso legge e scrive i byte da e nel relativo archivio di backup. I flussi che si connettono agli archivi di backup sono chiamati flussi di base. I flussi di base hanno costruttori con i parametri necessari per connettere il flusso all'archivio di backup. FileStream, ad esempio, ha costruttori che specificano un parametro del percorso, che specifica come il file verrà condiviso dai processi.

La progettazione delle classi System.IO consente una composizione dei flussi semplificata. I flussi di base possono essere associati a uno o più flussi pass-through che forniscono la funzionalità desiderata. Un lettore o un writer può essere collegato alla fine della catena, in modo che i tipi preferiti possano essere letti o scritti facilmente.

Gli esempi di codice seguenti creano un FileStream per il file esistente MyFile.txt in modo da inserire nel buffer MyFile.txt. Si noti che gli elementi FileStream vengono memorizzati nel buffer per impostazione predefinita.

Importante

Gli esempi presuppongono che un file denominato MyFile.txt esista già nella stessa cartella dell'app.

Esempio: Usare StreamReader

L'esempio seguente crea un elemento StreamReader per leggere i caratteri da FileStream, che viene passato a StreamReader come argomento del costruttore. StreamReader.ReadLine legge finché StreamReader.Peek non trova più caratteri.

using System;
using System.IO;

public class CompBuf
{
    private const string FILE_NAME = "MyFile.txt";

    public static void Main()
    {
        if (!File.Exists(FILE_NAME))
        {
            Console.WriteLine($"{FILE_NAME} does not exist!");
            return;
        }
        // Create an instance of StreamReader characters from the file.
        using (StreamReader sr = new StreamReader(FILE_NAME))
        {
            string input;
            // While not at the end of the file, read lines from the file.
            while (sr.Peek() > -1)
            {
                input = sr.ReadLine();
                Console.WriteLine(input);
            }
        }
    }
}
Imports System.IO

Public Class CompBuf
    Private Const FILE_NAME As String = "MyFile.txt"

    Public Shared Sub Main()
        If Not File.Exists(FILE_NAME) Then
            Console.WriteLine($"{FILE_NAME} does not exist!")
            Return
        End If
        Dim fsIn As new FileStream(FILE_NAME, FileMode.Open, _
            FileAccess.Read, FileShare.Read)
        ' Create an instance of StreamReader that can read
        ' characters from the FileStream.
        Using sr As New StreamReader(fsIn)
            Dim input As String
            ' While not at the end of the file, read lines from the file.
            While sr.Peek() > -1
                input = sr.ReadLine()
                Console.WriteLine(input)
            End While
        End Using
    End Sub
End Class

Esempio: Usare BinaryReader

L'esempio seguente crea un elemento BinaryReader per leggere i byte da FileStream, che viene passato a BinaryReader come argomento del costruttore. ReadByte legge finché PeekChar non trova più byte.

using System;
using System.IO;

public class ReadBuf
{
    private const string FILE_NAME = "MyFile.txt";

    public static void Main()
    {
        if (!File.Exists(FILE_NAME))
        {
            Console.WriteLine($"{FILE_NAME} does not exist.");
            return;
        }
        using (FileStream f = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            // Create an instance of BinaryReader that can
            // read bytes from the FileStream.
            using (BinaryReader br = new BinaryReader(f))
            {
                byte input;
                // While not at the end of the file, read lines from the file.
                while (br.PeekChar() > -1)
                {
                    input = br.ReadByte();
                    Console.WriteLine(input);
                }
            }
        }
    }
}
Imports System.IO

Public Class ReadBuf
    Private Const FILE_NAME As String = "MyFile.txt"

    Public Shared Sub Main()
        If Not File.Exists(FILE_NAME) Then
            Console.WriteLine($"{FILE_NAME} does not exist.")
            Return
        End If
        Dim f As New FileStream(FILE_NAME, FileMode.Open, _
            FileAccess.Read, FileShare.Read)
        ' Create an instance of BinaryReader that can
        ' read bytes from the FileStream.
        Using br As new BinaryReader(f)
            Dim input As Byte
            ' While not at the end of the file, read lines from the file.
            While br.PeekChar() > -1
                input = br.ReadByte()
                Console.WriteLine(input)
            End While
        End Using
    End Sub
End Class

Vedi anche