BinaryReader.ReadChars(Int32) Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Считывает указанное число символов из текущего потока, возвращает данные в массиве символов и перемещает текущую позицию в соответствии с Encoding используемым и определенным символом, считываемым из потока.
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()
Параметры
- count
- Int32
Число символов для чтения.
Возвращаемое значение
Массив символов, содержащий данные, считывающиеся из базового потока. Это может быть меньше числа символов, запрошенных при достижении конца потока.
Исключения
Число декодированных символов для чтения больше count. Это может произойти, если декодатор Юникод возвращает резервные символы или суррогатную пару.
Поток закрыт.
Произошла ошибка ввода-вывода.
count отрицательно.
Примеры
В следующем примере кода показано, как считывать и записывать данные с помощью памяти в качестве резервного хранилища.
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
Комментарии
BinaryReader не восстанавливает позицию файла после неудачной операции чтения.
При чтении из сетевых потоков в некоторых редких случаях ReadChars метод может считывать дополнительный символ из потока, если BinaryReader он был создан с кодировкой Юникода. В этом случае можно использовать ReadBytes метод для чтения массива байтов фиксированной длины, а затем передать этот массив в ReadChars метод.