StreamReader.DiscardBufferedData 메서드

정의

내부 버퍼를 지웁니다.

public:
 void DiscardBufferedData();
public void DiscardBufferedData ();
member this.DiscardBufferedData : unit -> unit
Public Sub DiscardBufferedData ()

예제

다음 예제에서는 내부 버퍼와 기본 스트림을 DiscardBufferedData 동기화하기 위해 메서드를 호출해야 하는 시나리오를 보여 있습니다. 예제의 파일은 위치를 설명하는 데 사용되며 텍스트 abcdefghijklmnopqrstuvwxyz로 구성됩니다. 데이터를 읽은 후 를 호출 DiscardBufferedData 하면 예제가 예상대로 작동합니다. 처음 15자를 읽은 후 위치는 오프셋 값 2로 다시 설정되고 나머지 문자는 모두 읽습니다. 에 대한 호출을 DiscardBufferedData제거하면 예제가 예상대로 작동하지 않습니다. 처음 15자를 읽지만 기본 스트림의 위치만 다시 설정됩니다. 개체의 StreamReader 내부 버퍼는 여전히 16번째 문자에 있습니다. 따라서 는 ReadToEnd 버퍼의 모든 문자와 초기화 위치에서 시작하는 기본 스트림의 문자를 반환합니다.

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\alphabet.txt";

        using (StreamReader sr = new StreamReader(path))
        {
            char[] c = null;

            c = new char[15];
            sr.Read(c, 0, c.Length);
            Console.WriteLine("first 15 characters:");
            Console.WriteLine(c);
            // writes - "abcdefghijklmno"

            sr.DiscardBufferedData();
            sr.BaseStream.Seek(2, SeekOrigin.Begin);
            Console.WriteLine("\nBack to offset 2 and read to end: ");
            Console.WriteLine(sr.ReadToEnd());
            // writes - "cdefghijklmnopqrstuvwxyz"
            // without DiscardBufferedData, writes - "pqrstuvwxyzcdefghijklmnopqrstuvwxyz"
        }
    }
}
Imports System.IO

Module Module1

    Sub Main()
        Dim path As String = "c:\temp\alphabet.txt"

        Dim sr As StreamReader = New StreamReader(path)
        Dim c(14) As Char

        sr.Read(c, 0, c.Length)
        Console.WriteLine("first 15 characters:")
        Console.WriteLine(c)
        ' writes - "abcdefghijklmno"

        sr.DiscardBufferedData()
        sr.BaseStream.Seek(2, SeekOrigin.Begin)
        Console.WriteLine(Environment.NewLine & "Back to offset 2 and read to end: ")
        Console.WriteLine(sr.ReadToEnd())
        ' writes - "cdefghijklmnopqrstuvwxyz"
        ' without DiscardBufferedData, writes - "pqrstuvwxyzcdefghijklmnopqrstuvwxyz"
        sr.Close()
    End Sub

End Module

설명

메서드를 DiscardBufferedData 사용하여 개체의 내부 버퍼를 다시 설정합니다 StreamReader . 내부 버퍼의 위치와 가 일치하지 않는 경우에만 이 메서드를 BaseStream 호출해야 합니다. 버퍼로 데이터를 읽은 다음 기본 스트림에서 새 위치를 검색할 때 이러한 위치가 일치하지 않습니다. 이 메서드는 성능이 저하되며 개체 내용 StreamReader 의 일부를 두 번 이상 읽으려는 경우와 같이 절대적으로 필요한 경우에만 사용해야 합니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

적용 대상

추가 정보