BinaryReader.ReadChar Метод

Определение

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

public:
 virtual char ReadChar();
public virtual char ReadChar ();
abstract member ReadChar : unit -> char
override this.ReadChar : unit -> char
Public Overridable Function ReadChar () As Char

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

Char

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

Исключения

Достигнут конец потока.

Поток закрыт.

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

Выполнено чтение символа-заместителя.

Примеры

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

using namespace System;
using namespace System::IO;
int main()
{
   int i;
   array<Char>^invalidPathChars = Path::InvalidPathChars;
   MemoryStream^ memStream = gcnew MemoryStream;
   BinaryWriter^ binWriter = gcnew BinaryWriter( memStream );
   
   // Write to memory.
   binWriter->Write( "Invalid file path characters are: " );
   for ( i = 0; i < invalidPathChars->Length; i++ )
   {
      binWriter->Write( invalidPathChars[ i ] );

   }
   
   // Create the reader using the same MemoryStream 
   // as used with the writer.
   BinaryReader^ binReader = gcnew BinaryReader( memStream );
   
   // Set Position to the beginning of the stream.
   binReader->BaseStream->Position = 0;
   
   // Read the data from memory and write it to the console.
   Console::Write( binReader->ReadString() );
   array<Char>^memoryData = gcnew array<Char>(memStream->Length - memStream->Position);
   for ( i = 0; i < memoryData->Length; i++ )
   {
      memoryData[ i ] = binReader->ReadChar();

   }
   Console::WriteLine( memoryData );
}
using System;
using System.IO;

class BinaryRW
{
    static void Main()
    {
        int i = 0;
        char[] invalidPathChars = Path.InvalidPathChars;
        MemoryStream memStream = new MemoryStream();
        BinaryWriter binWriter = new BinaryWriter(memStream);

        // Write to memory.
        binWriter.Write("Invalid file path characters are: ");
        for(i = 0; i < invalidPathChars.Length; i++)
        {
            binWriter.Write(invalidPathChars[i]);
        }

        // Create the reader using the same MemoryStream
        // as used with the writer.
        BinaryReader binReader = new BinaryReader(memStream);

        // Set Position to the beginning of the stream.
        memStream.Position = 0;

        // Read the data from memory and write it to the console.
        Console.Write(binReader.ReadString());
        char[] memoryData =
            new char[memStream.Length - memStream.Position];
        for(i = 0; i < memoryData.Length; i++)
        {
            memoryData[i] = binReader.ReadChar();
        }
        Console.WriteLine(memoryData);
    }
}
open System.IO

let invalidPathChars = Path.GetInvalidPathChars()
let memStream = new MemoryStream()
let binWriter = new BinaryWriter(memStream)

// Write to memory.
binWriter.Write "Invalid file path characters are: "
for i = 0 to invalidPathChars.Length - 1 do
    binWriter.Write invalidPathChars[i]

// Create the reader using the same MemoryStream
// as used with the writer.
let binReader = new BinaryReader(memStream)

// Set Position to the beginning of the stream.
memStream.Position <- 0

// Read the data from memory and write it to the console.
printf $"{binReader.ReadString()}"
let memoryData = Array.zeroCreate<char> (int (memStream.Length - memStream.Position))
for i = 0 to memoryData.Length - 1 do
    memoryData[i] <- binReader.ReadChar()
printfn $"{memoryData}"
Imports System.IO

Public Class BinaryRW

    Shared Sub Main()
    
        Dim i As Integer = 0
        Dim invalidPathChars() As Char = Path.InvalidPathChars
        Dim memStream As new MemoryStream()
        Dim binWriter As New BinaryWriter(memStream)

        ' Write to memory.
        binWriter.Write("Invalid file path characters are: ")
        For i = 0 To invalidPathChars.Length - 1
            binWriter.Write(invalidPathChars(i))
        Next i

        ' Create the reader using the same MemoryStream 
        ' as used with the writer.
        Dim binReader As New BinaryReader(memStream)

        ' Set Position to the beginning of the stream.
        memStream.Position = 0

        ' Read the data from memory and write it to the console.
        Console.Write(binReader.ReadString())
        Dim memoryData( _
            CInt(memStream.Length - memStream.Position) - 1) As Char
        For i = 0 To memoryData.Length - 1
            memoryData(i) = binReader.ReadChar()
        Next i
        Console.WriteLine(memoryData)
    
    End Sub
End Class

Комментарии

ReadChar Если метод пытается прочитать суррогатный символ в потоке, будет создано исключение, а позиция в потоке будет выполнена. Позиция восстанавливается в исходном расположении до ReadChar вызова, если поток доступен для поиска; однако, если поток недоступен, позиция не будет исправлена. Если суррогатные символы можно ожидать в потоке, используйте ReadChars этот метод.

Из-за конфликтов форматирования данных не рекомендуется использовать этот метод со следующими кодировками:

  • UTF-7

  • ISO-2022-JP

  • ISCII

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

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

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