StreamReader.Read Метод

Определение

Считывает следующий символ или следующий набор символов из входного потока.

Перегрузки

Read()

Выполняет чтение следующего символа из входного потока и перемещает положение символа на одну позицию вперед.

Read(Span<Char>)

Считывает символы из текущего потока в диапазон.

Read(Char[], Int32, Int32)

Считывает заданное максимальное количество символов из текущего потока в буфер начиная с заданного индекса.

Read()

Выполняет чтение следующего символа из входного потока и перемещает положение символа на одну позицию вперед.

public:
 override int Read();
public override int Read ();
override this.Read : unit -> int
Public Overrides Function Read () As Integer

Возвращаемое значение

Int32

Следующий символ из входного потока, представленный в виде объекта Int32, или значение -1, если больше нет доступных символов.

Исключения

Ошибка ввода-вывода.

Примеры

В следующем примере кода демонстрируется простое использование Read метода.

using namespace System;
using namespace System::IO;
int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   try
   {
      if ( File::Exists( path ) )
      {
         File::Delete( path );
      }
      StreamWriter^ sw = gcnew StreamWriter( path );
      try
      {
         sw->WriteLine( "This" );
         sw->WriteLine( "is some text" );
         sw->WriteLine( "to test" );
         sw->WriteLine( "Reading" );
      }
      finally
      {
         delete sw;
      }

      StreamReader^ sr = gcnew StreamReader( path );
      try
      {
         while ( sr->Peek() >= 0 )
         {
            Console::Write( (Char)sr->Read() );
         }
      }
      finally
      {
         delete sr;
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "The process failed: {0}", e );
   }
}
using System;
using System.IO;

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

        try
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }

            using (StreamWriter sw = new StreamWriter(path))
            {
                sw.WriteLine("This");
                sw.WriteLine("is some text");
                sw.WriteLine("to test");
                sw.WriteLine("Reading");
            }

            using (StreamReader sr = new StreamReader(path))
            {
                while (sr.Peek() >= 0)
                {
                    Console.Write((char)sr.Read());
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
Imports System.IO
Imports System.Text

Public Class Test

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

        Try
            If File.Exists(path) Then
                File.Delete(path)
            End If

            Dim sw As StreamWriter = New StreamWriter(path)
            sw.WriteLine("This")
            sw.WriteLine("is some text")
            sw.WriteLine("to test")
            sw.WriteLine("Reading")
            sw.Close()

            Dim sr As StreamReader = New StreamReader(path)

            Do While sr.Peek() >= 0
                Console.Write(Convert.ToChar(sr.Read()))
            Loop
            sr.Close()
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

В следующем примере кода показано чтение одного символа с помощью Read() перегрузки метода, форматирование выходных данных ASCII в виде десятичного и шестнадцатеричного числа.

using namespace System;
using namespace System::IO;
int main()
{
   
   //Create a FileInfo instance representing an existing text file.
   FileInfo^ MyFile = gcnew FileInfo( "c:\\csc.txt" );
   
   //Instantiate a StreamReader to read from the text file.
   StreamReader^ sr = MyFile->OpenText();
   
   //Read a single character.
   int FirstChar = sr->Read();
   
   //Display the ASCII number of the character read in both decimal and hexadecimal format.
   Console::WriteLine( "The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.", FirstChar, FirstChar );
   
   //
   sr->Close();
}
using System;
using System.IO;

class StrmRdrRead
{
public static void Main()
    {
    //Create a FileInfo instance representing an existing text file.
    FileInfo MyFile=new FileInfo(@"c:\csc.txt");
    //Instantiate a StreamReader to read from the text file.
    StreamReader sr=MyFile.OpenText();
    //Read a single character.
    int FirstChar=sr.Read();
    //Display the ASCII number of the character read in both decimal and hexadecimal format.
    Console.WriteLine("The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.",
        FirstChar, FirstChar);
    //
    sr.Close();
    }
}
Imports System.IO

Class StrmRdrRead
   
   Public Shared Sub Main()
      'Create a FileInfo instance representing an existing text file.
      Dim MyFile As New FileInfo("c:\csc.txt")
      'Instantiate a StreamReader to read from the text file.
      Dim sr As StreamReader = MyFile.OpenText()
      'Read a single character.
      Dim FirstChar As Integer = sr.Read()
      'Display the ASCII number of the character read in both decimal and hexadecimal format.
      Console.WriteLine("The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.", FirstChar, FirstChar)
      sr.Close()
   End Sub
End Class

Комментарии

Этот метод переопределяет метод TextReader.Read.

Этот метод возвращает целое число, чтобы он мог вернуть значение-1, если достигнут конец потока. Если вы управляете положением базового потока после считывания данных в буфер, расположение базового потока может не соответствовать положению внутреннего буфера. Чтобы сбросить внутренний буфер, вызовите DiscardBufferedData метод, однако этот метод снижает производительность и должен вызываться только при крайней необходимости.

Список общих задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к

Read(Span<Char>)

Считывает символы из текущего потока в диапазон.

public:
 override int Read(Span<char> buffer);
public override int Read (Span<char> buffer);
override this.Read : Span<char> -> int
Public Overrides Function Read (buffer As Span(Of Char)) As Integer

Параметры

buffer
Span<Char>

При возврате этого метода содержит указанный диапазон символов, в котором значения заменены символами, считанными из текущего источника.

Возвращаемое значение

Int32

Число символов, которые были считаны, или значение 0, если к концу потока не было считано никаких данных. Это число будет не больше длины buffer в зависимости от доступности данных в потоке.

Исключения

Число символов, считанных из потока, превышает длину buffer.

buffer имеет значение null.

Применяется к

Read(Char[], Int32, Int32)

Считывает заданное максимальное количество символов из текущего потока в буфер начиная с заданного индекса.

public:
 override int Read(cli::array <char> ^ buffer, int index, int count);
public override int Read (char[] buffer, int index, int count);
override this.Read : char[] * int * int -> int
Public Overrides Function Read (buffer As Char(), index As Integer, count As Integer) As Integer

Параметры

buffer
Char[]

При возвращении данного метода содержит заданный массив знаков, в котором значения в интервале между index и (index + count – 1) заменены знаками, считанными из текущего источника.

index
Int32

Индекс buffer, с которого требуется начать запись.

count
Int32

Максимальное число считываемых символов.

Возвращаемое значение

Int32

Число символов, которые были считаны, или значение 0, если к концу потока не было считано никаких данных. Это число будет не больше параметра count, в зависимости от доступности данных в потоке.

Исключения

Длина буфера минус index меньше count.

buffer имеет значение null.

index или count является отрицательным значением.

Ошибка ввода-вывода, например "Поток закрыт".

Примеры

Следующий пример кода считывает пять символов за раз, пока не будет достигнут конец файла.

using namespace System;
using namespace System::IO;

int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   try
   {
      if ( File::Exists( path ) )
      {
         File::Delete( path );
      }
      StreamWriter^ sw = gcnew StreamWriter( path );
      try
      {
         sw->WriteLine( "This" );
         sw->WriteLine( "is some text" );
         sw->WriteLine( "to test" );
         sw->WriteLine( "Reading" );
      }
      finally
      {
         delete sw;
      }

      StreamReader^ sr = gcnew StreamReader( path );
      try
      {
         //This is an arbitrary size for this example.
         array<Char>^c = nullptr;
         while ( sr->Peek() >= 0 )
         {
            c = gcnew array<Char>(5);
            sr->Read( c, 0, c->Length );
            
            //The output will look odd, because
            //only five characters are read at a time.
            Console::WriteLine( c );
         }
      }
      finally
      {
         delete sr;
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "The process failed: {0}", e );
   }
}
using System;
using System.IO;

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

        try
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }

            using (StreamWriter sw = new StreamWriter(path))
            {
                sw.WriteLine("This");
                sw.WriteLine("is some text");
                sw.WriteLine("to test");
                sw.WriteLine("Reading");
            }

            using (StreamReader sr = new StreamReader(path))
            {
                //This is an arbitrary size for this example.
                char[] c = null;

                while (sr.Peek() >= 0)
                {
                    c = new char[5];
                    sr.Read(c, 0, c.Length);
                    //The output will look odd, because
                    //only five characters are read at a time.
                    Console.WriteLine(c);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
Imports System.IO
Imports System.Text

Public Class Test

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

        Try
            If File.Exists(path) Then
                File.Delete(path)
            End If

            Dim sw As StreamWriter = New StreamWriter(path)
            sw.WriteLine("This")
            sw.WriteLine("is some text")
            sw.WriteLine("to test")
            sw.WriteLine("Reading")
            sw.Close()

            Dim sr As StreamReader = New StreamReader(path)

            Do While sr.Peek() >= 0
                'This is an arbitrary size for this example.
                Dim c(5) As Char
                sr.Read(c, 0, c.Length)
                'The output will look odd, because
                'only five characters are read at a time.
                Console.WriteLine(c)
            Loop
            sr.Close()
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

Комментарии

Этот метод переопределяет метод TextReader.Read.

Этот метод возвращает целое число, чтобы он мог вернуть значение 0, если достигнут конец потока.

При использовании Read метода более эффективно использовать буфер, имеющий тот же размер, что и внутренний буфер потока, где для внутреннего буфера задается нужный размер блока, и значение всегда считывается меньше размера блока. Если размер внутреннего буфера не был указан при создании потока, его размер по умолчанию составляет 4 КБ (4096 байт). Если вы управляете положением базового потока после считывания данных в буфер, расположение базового потока может не соответствовать положению внутреннего буфера. Чтобы сбросить внутренний буфер, вызовите DiscardBufferedData метод, однако этот метод снижает производительность и должен вызываться только при крайней необходимости.

Этот метод возвращает значение, после того как число символов, указанных в count параметре, считывается, или достигнут конец файла. ReadBlock является блокирующей версией Read .

Список общих задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к