BinaryReader.ReadChars(Int32) Método

Definição

Lê o número especificado de caracteres do fluxo atual, retorna os dados em uma matriz de caracteres e avança a posição atual de acordo com o Encoding caractere usado e específico que está sendo lido do fluxo.

public:
 virtual cli::array <char> ^ ReadChars(int count);
public virtual char[] ReadChars(int count);
abstract member ReadChars : int -> char[]
override this.ReadChars : int -> char[]
Public Overridable Function ReadChars (count As Integer) As Char()

Parâmetros

count
Int32

O número de caracteres a serem lidos.

Retornos

Char[]

Uma matriz de caracteres que contém dados lidos do fluxo subjacente. Isso pode ser menor do que o número de caracteres solicitados se o final do fluxo for atingido.

Exceções

O número de caracteres decodificados a serem lidos é maior que count. Isso pode acontecer se um decodificador Unicode retornar caracteres de fallback ou um par alternativo.

O fluxo está fechado.

Ocorreu um erro de E/S.

count é negativo.

Exemplos

O exemplo de código a seguir mostra como ler e gravar dados usando a memória como um repositório de backup.

using System;
using System.IO;

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

        // Write to memory.
        binWriter.Write("Invalid file path characters are: ");
        binWriter.Write(Path.InvalidPathChars);

        // 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());
        Console.WriteLine(binReader.ReadChars(
            (int)(memStream.Length - memStream.Position)));
    }
}
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: "
binWriter.Write invalidPathChars

// 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()}"
printfn $"{binReader.ReadChars(int (memStream.Length - memStream.Position))}"
Imports System.IO

Public Class BinaryRW

    Shared Sub Main()
    
        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: ")
        binWriter.Write(Path.InvalidPathChars)

        ' 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())
        Console.WriteLine(binReader.ReadChars( _
            CInt(memStream.Length - memStream.Position)))
    
    End Sub
End Class

Comentários

BinaryReader não restaura a posição do arquivo após uma operação de leitura malsucedida.

Ao ler de fluxos de rede, em alguns casos raros, o ReadChars método poderá ler um caractere extra do fluxo se ele BinaryReader tiver sido construído com codificação Unicode. Se isso ocorrer, você poderá usar o ReadBytes método para ler uma matriz de bytes de comprimento fixo e, em seguida, passar essa matriz para o ReadChars método.

Aplica-se a

Confira também