Tworzenie strumieni

Magazyn zapasowy jest nośnikiem magazynu, takim jak dysk lub pamięć. Każdy inny magazyn zapasowy implementuje swój własny strumień jako implementację Stream klasy.

Każdy typ strumienia odczytuje i zapisuje bajty z i do danego magazynu kopii zapasowych. Strumienie, które łączą się z magazynami zapasowymi, są nazywane strumieniami podstawowymi. Strumienie podstawowe mają konstruktory z parametrami niezbędnymi do połączenia strumienia z magazynem zapasowym. Na przykład FileStream konstruktory, które określają parametr ścieżki, który określa sposób udostępniania pliku przez procesy.

Projekt System.IO klas zapewnia uproszczoną kompozycję strumienia. Możesz dołączyć strumienie podstawowe do jednego lub większej liczby strumieni przekazywania, które zapewniają odpowiednią funkcjonalność. Możesz dołączyć czytelnika lub moduł zapisywania na końcu łańcucha, aby można było łatwo odczytywać lub zapisywać preferowane typy.

Poniższe przykłady kodu tworzą element FileStream wokół istniejącej MyFile.txt w celu buforowania MyFile.txt. Należy pamiętać, że plik Strumienie są domyślnie buforowane.

Ważne

W przykładach przyjęto założenie, że plik o nazwie MyFile.txt już istnieje w tym samym folderze co aplikacja.

Przykład: Używanie elementu StreamReader

Poniższy przykład tworzy element do StreamReader odczytu znaków z elementu FileStream, który jest przekazywany do elementu StreamReader jako argument konstruktora. StreamReader.ReadLine następnie odczytuje, dopóki StreamReader.Peek nie znajdzie więcej znaków.

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

Przykład: Użyj elementu BinaryReader

Poniższy przykład tworzy obiekt do BinaryReader odczytu bajtów z elementu FileStream, który jest przekazywany do elementu BinaryReader jako argument konstruktora. ReadByte następnie odczytuje, dopóki PeekChar nie znajdzie więcej bajtów.

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

Zobacz też