BinaryReader.BaseStream Свойство
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Предоставляет доступ к базовому потоку объекта BinaryReader.
public:
virtual property System::IO::Stream ^ BaseStream { System::IO::Stream ^ get(); };
public virtual System.IO.Stream BaseStream { get; }
member this.BaseStream : System.IO.Stream
Public Overridable ReadOnly Property BaseStream As Stream
Базовый поток, связанный с объектом BinaryReader
.
В следующем примере кода показано, как считывать и записывать Double
данные в память с помощью BinaryReader
классов и BinaryWriter поверх MemoryStream класса . MemoryStream
Только считывает и записывает Byte
данные.
using namespace System;
using namespace System::IO;
int main()
{
int i;
const int arrayLength = 1000;
// Create random data to write to the stream.
array<double>^dataArray = gcnew array<double>(arrayLength);
Random^ randomGenerator = gcnew Random;
for ( i = 0; i < arrayLength; i++ )
{
dataArray[ i ] = 100.1 * randomGenerator->NextDouble();
}
BinaryWriter^ binWriter = gcnew BinaryWriter( gcnew MemoryStream );
try
{
// Write data to the stream.
Console::WriteLine( "Writing data to the stream." );
i = 0;
for ( i = 0; i < arrayLength; i++ )
{
binWriter->Write( dataArray[ i ] );
}
// Create a reader using the stream from the writer.
BinaryReader^ binReader = gcnew BinaryReader( binWriter->BaseStream );
// Return to the beginning of the stream.
binReader->BaseStream->Position = 0;
try
{
// Read and verify the data.
i = 0;
Console::WriteLine( "Verifying the written data." );
for ( i = 0; i < arrayLength; i++ )
{
if ( binReader->ReadDouble() != dataArray[ i ] )
{
Console::WriteLine( "Error writing data." );
break;
}
}
Console::WriteLine( "The data was written and verified." );
}
catch ( EndOfStreamException^ e )
{
Console::WriteLine( "Error writing data: {0}.", e->GetType()->Name );
}
}
finally
{
binWriter->Close();
}
}
using System;
using System.IO;
class BinaryRW
{
static void Main()
{
int i;
const int arrayLength = 1000;
// Create random data to write to the stream.
Random randomGenerator = new Random();
double[] dataArray = new double[arrayLength];
for(i = 0; i < arrayLength; i++)
{
dataArray[i] = 100.1 * randomGenerator.NextDouble();
}
using(BinaryWriter binWriter =
new BinaryWriter(new MemoryStream()))
{
// Write the data to the stream.
Console.WriteLine("Writing data to the stream.");
for(i = 0; i < arrayLength; i++)
{
binWriter.Write(dataArray[i]);
}
// Create a reader using the stream from the writer.
using(BinaryReader binReader =
new BinaryReader(binWriter.BaseStream))
{
try
{
// Return to the beginning of the stream.
binReader.BaseStream.Position = 0;
// Read and verify the data.
Console.WriteLine("Verifying the written data.");
for(i = 0; i < arrayLength; i++)
{
if(binReader.ReadDouble() != dataArray[i])
{
Console.WriteLine("Error writing data.");
break;
}
}
Console.WriteLine("The data was written " +
"and verified.");
}
catch(EndOfStreamException e)
{
Console.WriteLine("Error writing data: {0}.",
e.GetType().Name);
}
}
}
}
}
open System
open System.IO
let arrayLength = 1000
// Create random data to write to the stream.
let randomGenerator = Random()
let dataArray =
Array.init arrayLength (fun _ -> 100.1 * randomGenerator.NextDouble())
do
use binWriter = new BinaryWriter(new MemoryStream())
// Write the data to the stream.
printfn $"Writing data to the stream."
for num in dataArray do
binWriter.Write num
// Create a reader using the stream from the writer.
use binReader = new BinaryReader(binWriter.BaseStream)
try
// Return to the beginning of the stream.
binReader.BaseStream.Position <- 0
// Read and verify the data.
printfn "Verifying the written data."
for num in dataArray do
if binReader.ReadDouble() <> num then
printfn "Error writing data."
printfn "The data was written and verified."
with :? EndOfStreamException as e ->
printfn $"Error writing data: {e.GetType().Name}."
Imports System.IO
Public Class BinaryRW
Shared Sub Main()
Dim i As Integer
Const upperBound As Integer = 1000
' Create random data to write to the stream.
Dim dataArray(upperBound) As Double
Dim randomGenerator As New Random()
For i = 0 To upperBound
dataArray(i) = 100.1 * randomGenerator.NextDouble()
Next i
Dim binWriter As New BinaryWriter(New MemoryStream())
Try
' Write data to the stream.
Console.WriteLine("Writing data to the stream.")
For i = 0 To upperBound
binWriter.Write(dataArray(i))
Next i
' Create a reader using the stream from the writer.
Dim binReader As New BinaryReader(binWriter.BaseStream)
' Return to the beginning of the stream.
binReader.BaseStream.Position = 0
' Read and verify the data.
Try
Console.WriteLine("Verifying the written data.")
For i = 0 To upperBound
If binReader.ReadDouble() <> dataArray(i) Then
Console.WriteLine("Error writing data.")
Exit For
End If
Next i
Console.WriteLine("The data was written and verified.")
Catch ex As EndOfStreamException
Console.WriteLine("Error writing data: {0}.", _
ex.GetType().Name)
End Try
Finally
binWriter.Close()
End Try
End Sub
End Class
Назар аударыңыз!
Использование базового потока во время чтения или при использовании BinaryReader
может привести к потере данных и повреждению. Например, одни и те же байты могут быть прочитаны несколько раз, байты могут быть пропущены или чтение символов может стать непредсказуемым.
Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.
Өнім | Нұсқалар |
---|---|
.NET | Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9 |
.NET Framework | 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1 |
.NET Standard | 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1 |
UWP | 10.0 |
.NET кері байланысы
.NET — бастапқы коды ашық жоба. Пікір қалдыру үшін сілтемені таңдаңыз: