BinaryWriter.Write Metódus
Definíció
Fontos
Egyes információk olyan, kiadás előtti termékekre vonatkoznak, amelyek a kiadásig még jelentősen módosulhatnak. A Microsoft nem vállal kifejezett vagy törvényi garanciát az itt megjelenő információért.
Értéket ír az aktuális streambe.
Túlterhelések
| Name | Description |
|---|---|
| Write(Char[], Int32, Int32) |
Egy karaktertömb egy szakaszát az aktuális streambe írja, és a stream aktuális pozícióját a |
| Write(Byte[], Int32, Int32) |
Egy bájttömb egy régióját írja az aktuális adatfolyamba. |
| Write(UInt64) |
Nyolcbájtos, aláíratlan egész számot ír az aktuális adatfolyamra, és nyolc bájttal lép előre a stream pozícióján. |
| Write(UInt32) |
Négybájtos, aláíratlan egész számot ír az aktuális adatfolyamra, és négy bájttal lép előre a stream pozícióján. |
| Write(UInt16) |
Kétbájtos, aláíratlan egész számot ír az aktuális adatfolyamra, és két bájttal lép előre a stream pozícióján. |
| Write(String) |
Egy hosszelőtagú sztringet ír erre a streamre a BinaryWriterstream aktuális kódolásában, és a használt kódolásnak és a streambe írt konkrét karaktereknek megfelelően alakítja tovább a stream aktuális pozícióját. |
| Write(Single) |
Négybájtos lebegőpontos értéket ír az aktuális streambe, és négy bájttal lép előre a stream pozícióján. |
| Write(SByte) |
Aláírt bájtot ír az aktuális streambe, és egy bájttal előrelépteti a stream pozícióját. |
| Write(ReadOnlySpan<Char>) |
Több karaktert ír az aktuális streambe, és a stream aktuális pozícióját a használt és esetleg a streambe írt konkrét karaktereknek megfelelően |
| Write(ReadOnlySpan<Byte>) |
Bájttartományt ír az aktuális streambe. |
| Write(Int64) |
Nyolcbájtos aláírt egész számot ír az aktuális streamre, és nyolc bájttal előrelép a stream pozícióján. |
| Write(Char[]) |
Karaktertömböt ír az aktuális streambe, és a használt és a streambe írt konkrét karaktereknek |
| Write(Int16) |
Kétbájtos aláírt egész számot ír az aktuális streambe, és két bájttal előrelépteti a stream pozícióját. |
| Write(Half) |
Kétbájtos lebegőpontos értéket ír az aktuális adatfolyamba, és két bájttal lép előre a stream pozícióján. |
| Write(Double) |
Nyolcbájtos lebegőpontos értéket ír az aktuális streambe, és nyolc bájttal lép előre a stream pozícióján. |
| Write(Decimal) |
Decimális értéket ír az aktuális adatfolyamra, és tizenhat bájttal lép előre a stream pozícióján. |
| Write(Char) |
Unicode-karaktert ír az aktuális streambe, és a használt és a streambe írt konkrét karaktereknek |
| Write(Byte[]) |
Bájttömböt ír a mögöttes adatfolyamba. |
| Write(Byte) |
Aláíratlan bájtot ír az aktuális adatfolyamra, és egy bájttal előrelépteti a stream pozícióját. |
| Write(Boolean) |
Egy bájtos |
| Write(Int32) |
Négybájtos aláírt egész számot ír az aktuális streamre, és négy bájttal előrelépteti a stream pozícióját. |
Write(Char[], Int32, Int32)
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Egy karaktertömb egy szakaszát az aktuális streambe írja, és a stream aktuális pozícióját a Encoding használt és esetleg a streambe írt konkrét karaktereknek megfelelően alakítja tovább.
public:
virtual void Write(cli::array <char> ^ chars, int index, int count);
public virtual void Write(char[] chars, int index, int count);
abstract member Write : char[] * int * int -> unit
override this.Write : char[] * int * int -> unit
Public Overridable Sub Write (chars As Char(), index As Integer, count As Integer)
Paraméterek
- chars
- Char[]
Az írandó adatokat tartalmazó karaktertömb.
- index
- Int32
Annak az első karakternek az indexe, amelyből chars olvasni és írni szeretne a streambe.
- count
- Int32
Az olvasási chars és a streambe írandó karakterek száma.
Kivételek
A puffer hossza mínusz index kisebb, mint count.
chars az null.
index vagy count negatív.
I/O-hiba történik.
A stream bezárult.
Példák
Az alábbi példakód bemutatja, hogyan olvashat és írhat adatokat memória használatával háttértárként.
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, 0, Path.InvalidPathChars.Length);
// 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());
int arraySize = (int)(memStream.Length - memStream.Position);
char[] memoryData = new char[arraySize];
binReader.Read(memoryData, 0, arraySize);
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: "
binWriter.Write(invalidPathChars, 0, invalidPathChars.Length)
// 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 arraySize = memStream.Length - memStream.Position |> int
let memoryData = Array.zeroCreate<char> arraySize
binReader.Read(memoryData, 0, arraySize) |> ignore
printfn $"{memoryData}"
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, 0, _
Path.InvalidPathChars.Length)
' 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 upperBound As Integer = _
CInt(memStream.Length - memStream.Position) - 1
Dim memoryData(upperBound) As Char
binReader.Read(memoryData, 0, upperBound)
Console.WriteLine(memoryData)
End Sub
End Class
Megjegyzések
A gyakori I/O-feladatok listáját a Gyakori I/O-feladatok című témakörben találja.
Lásd még
A következőre érvényes:
Write(Byte[], Int32, Int32)
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Egy bájttömb egy régióját írja az aktuális adatfolyamba.
public:
virtual void Write(cli::array <System::Byte> ^ buffer, int index, int count);
public virtual void Write(byte[] buffer, int index, int count);
abstract member Write : byte[] * int * int -> unit
override this.Write : byte[] * int * int -> unit
Public Overridable Sub Write (buffer As Byte(), index As Integer, count As Integer)
Paraméterek
- buffer
- Byte[]
Az írandó adatokat tartalmazó bájttömb.
- index
- Int32
Az első bájt indexe, amelyből buffer olvasni és írni szeretne a streambe.
- count
- Int32
A streamből buffer beolvasni és a streambe írni kívánt bájtok száma.
Kivételek
A puffer hossza mínusz index kisebb, mint count.
buffer az null.
index vagy count negatív.
I/O-hiba történik.
A stream bezárult.
Példák
Az alábbi példakód bemutatja, hogyan írhat bináris adatokat memória használatával háttértárként, majd ellenőrizheti, hogy az adatok helyesen írták-e.
using System;
using System.IO;
namespace BinaryRW
{
class Program
{
static void Main(string[] args)
{
const int arrayLength = 1000;
byte[] dataArray = new byte[arrayLength];
byte[] verifyArray = new byte[arrayLength];
new Random().NextBytes(dataArray);
using (BinaryWriter binWriter = new BinaryWriter(new MemoryStream()))
{
Console.WriteLine("Writing the data.");
binWriter.Write(dataArray, 0, arrayLength);
using (BinaryReader binReader = new BinaryReader(binWriter.BaseStream))
{
binReader.BaseStream.Position = 0;
if (binReader.Read(verifyArray, 0, arrayLength) != arrayLength)
{
Console.WriteLine("Error writing the data.");
return;
}
}
}
for (int i = 0; i < arrayLength; i++)
{
if (verifyArray[i] != dataArray[i])
{
Console.WriteLine("Error writing the data.");
return;
}
}
Console.WriteLine("The data was written and verified.");
}
}
}
open System
open System.IO
let arrayLength = 1000
let dataArray = Array.zeroCreate<byte> arrayLength
let verifyArray = Array.zeroCreate<byte> arrayLength
Random().NextBytes dataArray
do
use binWriter = new BinaryWriter(new MemoryStream())
printfn "Writing the data."
binWriter.Write(dataArray, 0, arrayLength)
use binReader = new BinaryReader(binWriter.BaseStream)
binReader.BaseStream.Position <- 0
if binReader.Read(verifyArray, 0, arrayLength) <> arrayLength then
printfn "Error writing the data."
else
for i = 0 to arrayLength - 1 do
if verifyArray[i] <> dataArray[i] then
printfn "Error writing the data."
else
printfn "The data was written and verified."
Imports System.IO
Module Module1
Sub Main()
Const upperBound As Integer = 1000
Dim dataArray(upperBound) As Byte
Dim verifyArray(upperBound) As Byte
Dim randomGenerator As New Random
randomGenerator.NextBytes(dataArray)
Using binWriter As New BinaryWriter(New MemoryStream())
Console.WriteLine("Writing the data.")
binWriter.Write(dataArray, 0, dataArray.Length)
Using binReader As New BinaryReader(binWriter.BaseStream)
binReader.BaseStream.Position = 0
If binReader.Read(verifyArray, 0, dataArray.Length) <> dataArray.Length Then
Console.WriteLine("Error writing the data.")
Return
End If
End Using
End Using
For i As Integer = 0 To upperBound
If verifyArray(i) <> dataArray(i) Then
Console.WriteLine("Error writing the data.")
Return
End If
Next i
Console.WriteLine("The data was written and verified.")
End Sub
End Module
Megjegyzések
A gyakori I/O-feladatok listáját a Gyakori I/O-feladatok című témakörben találja.
Lásd még
A következőre érvényes:
Write(UInt64)
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Fontos
Ez az API nem CLS-kompatibilis.
Nyolcbájtos, aláíratlan egész számot ír az aktuális adatfolyamra, és nyolc bájttal lép előre a stream pozícióján.
public:
virtual void Write(System::UInt64 value);
[System.CLSCompliant(false)]
public virtual void Write(ulong value);
[<System.CLSCompliant(false)>]
abstract member Write : uint64 -> unit
override this.Write : uint64 -> unit
Public Overridable Sub Write (value As ULong)
Paraméterek
- value
- UInt64
Az íráshoz használható nyolc bájtos, aláíratlan egész szám.
- Attribútumok
Kivételek
I/O-hiba történik.
A stream bezárult.
Megjegyzések
BinaryWriter ezt az adattípust kis endian formátumban tárolja.
A gyakori I/O-feladatok listáját a Gyakori I/O-feladatok című témakörben találja.
Lásd még
A következőre érvényes:
Write(UInt32)
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Fontos
Ez az API nem CLS-kompatibilis.
Négybájtos, aláíratlan egész számot ír az aktuális adatfolyamra, és négy bájttal lép előre a stream pozícióján.
public:
virtual void Write(System::UInt32 value);
[System.CLSCompliant(false)]
public virtual void Write(uint value);
[<System.CLSCompliant(false)>]
abstract member Write : uint32 -> unit
override this.Write : uint32 -> unit
Public Overridable Sub Write (value As UInteger)
Paraméterek
- value
- UInt32
Az íráshoz használható négy bájtos, aláíratlan egész szám.
- Attribútumok
Kivételek
I/O-hiba történik.
A stream bezárult.
Megjegyzések
BinaryWriter ezt az adattípust kis endian formátumban tárolja.
A gyakori I/O-feladatok listáját a Gyakori I/O-feladatok című témakörben találja.
Lásd még
A következőre érvényes:
Write(UInt16)
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Fontos
Ez az API nem CLS-kompatibilis.
Kétbájtos, aláíratlan egész számot ír az aktuális adatfolyamra, és két bájttal lép előre a stream pozícióján.
public:
virtual void Write(System::UInt16 value);
[System.CLSCompliant(false)]
public virtual void Write(ushort value);
[<System.CLSCompliant(false)>]
abstract member Write : uint16 -> unit
override this.Write : uint16 -> unit
Public Overridable Sub Write (value As UShort)
Paraméterek
- value
- UInt16
Az íráshoz használható két bájtos, aláíratlan egész szám.
- Attribútumok
Kivételek
I/O-hiba történik.
A stream bezárult.
Megjegyzések
BinaryWriter ezt az adattípust kis endian formátumban tárolja.
A gyakori I/O-feladatok listáját a Gyakori I/O-feladatok című témakörben találja.
Lásd még
A következőre érvényes:
Write(String)
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Egy hosszelőtagú sztringet ír erre a streamre a BinaryWriterstream aktuális kódolásában, és a használt kódolásnak és a streambe írt konkrét karaktereknek megfelelően alakítja tovább a stream aktuális pozícióját.
public:
virtual void Write(System::String ^ value);
public virtual void Write(string value);
abstract member Write : string -> unit
override this.Write : string -> unit
Public Overridable Sub Write (value As String)
Paraméterek
- value
- String
Az írandó érték.
Kivételek
I/O-hiba történik.
value az null.
A stream bezárult.
Példák
Az alábbi példakód bemutatja, hogyan tárolhatja és lekérheti az alkalmazásbeállításokat egy fájlban.
using System;
using System.IO;
using System.Text;
class ConsoleApplication
{
const string fileName = "AppSettings.dat";
static void Main()
{
WriteDefaultValues();
DisplayValues();
}
public static void WriteDefaultValues()
{
using (var stream = File.Open(fileName, FileMode.Create))
{
using (var writer = new BinaryWriter(stream, Encoding.UTF8, false))
{
writer.Write(1.250F);
writer.Write(@"c:\Temp");
writer.Write(10);
writer.Write(true);
}
}
}
public static void DisplayValues()
{
float aspectRatio;
string tempDirectory;
int autoSaveTime;
bool showStatusBar;
if (File.Exists(fileName))
{
using (var stream = File.Open(fileName, FileMode.Open))
{
using (var reader = new BinaryReader(stream, Encoding.UTF8, false))
{
aspectRatio = reader.ReadSingle();
tempDirectory = reader.ReadString();
autoSaveTime = reader.ReadInt32();
showStatusBar = reader.ReadBoolean();
}
}
Console.WriteLine("Aspect ratio set to: " + aspectRatio);
Console.WriteLine("Temp directory is: " + tempDirectory);
Console.WriteLine("Auto save time set to: " + autoSaveTime);
Console.WriteLine("Show status bar: " + showStatusBar);
}
}
}
open System.IO
open System.Text
let fileName = "AppSettings.dat"
let writeDefaultValues () =
use stream = File.Open(fileName, FileMode.Create)
use writer = new BinaryWriter(stream, Encoding.UTF8, false)
writer.Write 1.250F
writer.Write @"c:\Temp"
writer.Write 10
writer.Write true
let displayValues () =
if File.Exists fileName then
use stream = File.Open(fileName, FileMode.Open)
use reader = new BinaryReader(stream, Encoding.UTF8, false)
let aspectRatio = reader.ReadSingle()
let tempDirectory = reader.ReadString()
let autoSaveTime = reader.ReadInt32()
let showStatusBar = reader.ReadBoolean()
printfn $"Aspect ratio set to: {aspectRatio}"
printfn $"Temp directory is: {tempDirectory}"
printfn $"Auto save time set to: {autoSaveTime}"
printfn $"Show status bar: {showStatusBar}"
writeDefaultValues ()
displayValues ()
Imports System.IO
Module Module1
Const fileName As String = "AppSettings.dat"
Sub Main()
WriteDefaultValues()
DisplayValues()
End Sub
Sub WriteDefaultValues()
Using writer As BinaryWriter = New BinaryWriter(File.Open(fileName, FileMode.Create))
writer.Write(1.25F)
writer.Write("c:\Temp")
writer.Write(10)
writer.Write(True)
End Using
End Sub
Sub DisplayValues()
Dim aspectRatio As Single
Dim tempDirectory As String
Dim autoSaveTime As Integer
Dim showStatusBar As Boolean
If (File.Exists(fileName)) Then
Using reader As BinaryReader = New BinaryReader(File.Open(fileName, FileMode.Open))
aspectRatio = reader.ReadSingle()
tempDirectory = reader.ReadString()
autoSaveTime = reader.ReadInt32()
showStatusBar = reader.ReadBoolean()
End Using
Console.WriteLine("Aspect ratio set to: " & aspectRatio)
Console.WriteLine("Temp directory is: " & tempDirectory)
Console.WriteLine("Auto save time set to: " & autoSaveTime)
Console.WriteLine("Show status bar: " & showStatusBar)
End If
End Sub
End Module
Megjegyzések
A hosszelőtag azt jelenti, hogy ez a metódus először bájtban írja meg a sztring hosszát, amikor a példány aktuális kódolásával kódolja a BinaryWriter streamet. Ez az érték aláíratlan egész számként van megírva. Ez a metódus ezután ennyi bájtot ír a streambe.
Az "A" sztring például 1 hosszúságú, de UTF-16 kódolás esetén; a hossz 2 bájt, így az előtagban írt érték 2, a streambe pedig 3 bájt íródik, beleértve az előtagot is.
A gyakori I/O-feladatok listáját a Gyakori I/O-feladatok című témakörben találja.
Lásd még
A következőre érvényes:
Write(Single)
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Négybájtos lebegőpontos értéket ír az aktuális streambe, és négy bájttal lép előre a stream pozícióján.
public:
virtual void Write(float value);
public virtual void Write(float value);
abstract member Write : single -> unit
override this.Write : single -> unit
Public Overridable Sub Write (value As Single)
Paraméterek
- value
- Single
Az írandó négy bájtos lebegőpontos érték.
Kivételek
I/O-hiba történik.
A stream bezárult.
Példák
Az alábbi példakód bemutatja, hogyan tárolhatja és lekérheti az alkalmazásbeállításokat egy fájlban.
using System;
using System.IO;
using System.Text;
class ConsoleApplication
{
const string fileName = "AppSettings.dat";
static void Main()
{
WriteDefaultValues();
DisplayValues();
}
public static void WriteDefaultValues()
{
using (var stream = File.Open(fileName, FileMode.Create))
{
using (var writer = new BinaryWriter(stream, Encoding.UTF8, false))
{
writer.Write(1.250F);
writer.Write(@"c:\Temp");
writer.Write(10);
writer.Write(true);
}
}
}
public static void DisplayValues()
{
float aspectRatio;
string tempDirectory;
int autoSaveTime;
bool showStatusBar;
if (File.Exists(fileName))
{
using (var stream = File.Open(fileName, FileMode.Open))
{
using (var reader = new BinaryReader(stream, Encoding.UTF8, false))
{
aspectRatio = reader.ReadSingle();
tempDirectory = reader.ReadString();
autoSaveTime = reader.ReadInt32();
showStatusBar = reader.ReadBoolean();
}
}
Console.WriteLine("Aspect ratio set to: " + aspectRatio);
Console.WriteLine("Temp directory is: " + tempDirectory);
Console.WriteLine("Auto save time set to: " + autoSaveTime);
Console.WriteLine("Show status bar: " + showStatusBar);
}
}
}
open System.IO
open System.Text
let fileName = "AppSettings.dat"
let writeDefaultValues () =
use stream = File.Open(fileName, FileMode.Create)
use writer = new BinaryWriter(stream, Encoding.UTF8, false)
writer.Write 1.250F
writer.Write @"c:\Temp"
writer.Write 10
writer.Write true
let displayValues () =
if File.Exists fileName then
use stream = File.Open(fileName, FileMode.Open)
use reader = new BinaryReader(stream, Encoding.UTF8, false)
let aspectRatio = reader.ReadSingle()
let tempDirectory = reader.ReadString()
let autoSaveTime = reader.ReadInt32()
let showStatusBar = reader.ReadBoolean()
printfn $"Aspect ratio set to: {aspectRatio}"
printfn $"Temp directory is: {tempDirectory}"
printfn $"Auto save time set to: {autoSaveTime}"
printfn $"Show status bar: {showStatusBar}"
writeDefaultValues ()
displayValues ()
Imports System.IO
Module Module1
Const fileName As String = "AppSettings.dat"
Sub Main()
WriteDefaultValues()
DisplayValues()
End Sub
Sub WriteDefaultValues()
Using writer As BinaryWriter = New BinaryWriter(File.Open(fileName, FileMode.Create))
writer.Write(1.25F)
writer.Write("c:\Temp")
writer.Write(10)
writer.Write(True)
End Using
End Sub
Sub DisplayValues()
Dim aspectRatio As Single
Dim tempDirectory As String
Dim autoSaveTime As Integer
Dim showStatusBar As Boolean
If (File.Exists(fileName)) Then
Using reader As BinaryReader = New BinaryReader(File.Open(fileName, FileMode.Open))
aspectRatio = reader.ReadSingle()
tempDirectory = reader.ReadString()
autoSaveTime = reader.ReadInt32()
showStatusBar = reader.ReadBoolean()
End Using
Console.WriteLine("Aspect ratio set to: " & aspectRatio)
Console.WriteLine("Temp directory is: " & tempDirectory)
Console.WriteLine("Auto save time set to: " & autoSaveTime)
Console.WriteLine("Show status bar: " & showStatusBar)
End If
End Sub
End Module
Megjegyzések
BinaryWriter ezt az adattípust kis endian formátumban tárolja.
A gyakori I/O-feladatok listáját a Gyakori I/O-feladatok című témakörben találja.
Lásd még
A következőre érvényes:
Write(SByte)
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Fontos
Ez az API nem CLS-kompatibilis.
Aláírt bájtot ír az aktuális streambe, és egy bájttal előrelépteti a stream pozícióját.
public:
virtual void Write(System::SByte value);
[System.CLSCompliant(false)]
public virtual void Write(sbyte value);
[<System.CLSCompliant(false)>]
abstract member Write : sbyte -> unit
override this.Write : sbyte -> unit
Public Overridable Sub Write (value As SByte)
Paraméterek
- value
- SByte
Az írandó aláírt bájt.
- Attribútumok
Kivételek
I/O-hiba történik.
A stream bezárult.
Megjegyzések
A gyakori I/O-feladatok listáját a Gyakori I/O-feladatok című témakörben találja.
Lásd még
A következőre érvényes:
Write(ReadOnlySpan<Char>)
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Több karaktert ír az aktuális streambe, és a stream aktuális pozícióját a használt és esetleg a streambe írt konkrét karaktereknek megfelelően Encoding alakítja tovább.
public:
virtual void Write(ReadOnlySpan<char> chars);
public virtual void Write(ReadOnlySpan<char> chars);
abstract member Write : ReadOnlySpan<char> -> unit
override this.Write : ReadOnlySpan<char> -> unit
Public Overridable Sub Write (chars As ReadOnlySpan(Of Char))
Paraméterek
- chars
- ReadOnlySpan<Char>
Az írandó karakterekkel.
A következőre érvényes:
Write(ReadOnlySpan<Byte>)
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Bájttartományt ír az aktuális streambe.
public:
virtual void Write(ReadOnlySpan<System::Byte> buffer);
public virtual void Write(ReadOnlySpan<byte> buffer);
abstract member Write : ReadOnlySpan<byte> -> unit
override this.Write : ReadOnlySpan<byte> -> unit
Public Overridable Sub Write (buffer As ReadOnlySpan(Of Byte))
Paraméterek
- buffer
- ReadOnlySpan<Byte>
Az írandó bájtok száma.
A következőre érvényes:
Write(Int64)
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Nyolcbájtos aláírt egész számot ír az aktuális streamre, és nyolc bájttal előrelép a stream pozícióján.
public:
virtual void Write(long value);
public virtual void Write(long value);
abstract member Write : int64 -> unit
override this.Write : int64 -> unit
Public Overridable Sub Write (value As Long)
Paraméterek
- value
- Int64
Az íráshoz a nyolc bájtos aláírt egész szám.
Kivételek
I/O-hiba történik.
A stream bezárult.
Megjegyzések
BinaryWriter ezt az adattípust kis endian formátumban tárolja.
A gyakori I/O-feladatok listáját a Gyakori I/O-feladatok című témakörben találja.
Lásd még
A következőre érvényes:
Write(Char[])
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Karaktertömböt ír az aktuális streambe, és a használt és a streambe írt konkrét karaktereknek Encoding megfelelően alakítja tovább a stream aktuális pozícióját.
public:
virtual void Write(cli::array <char> ^ chars);
public virtual void Write(char[] chars);
abstract member Write : char[] -> unit
override this.Write : char[] -> unit
Public Overridable Sub Write (chars As Char())
Paraméterek
- chars
- Char[]
Az írandó adatokat tartalmazó karaktertömb.
Kivételek
chars az null.
A stream bezárult.
I/O-hiba történik.
Példák
Az alábbi példakód bemutatja, hogyan olvashat és írhat adatokat memória használatával háttértárként.
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
Megjegyzések
Az alábbi táblázat más tipikus vagy kapcsolódó I/O-feladatokra mutat be példákat.
| Ehhez... | Tekintse meg a jelen témakörben szereplő példát... |
|---|---|
| Szövegfájl létrehozása. | Útmutató: Szöveg írása fájlba |
| Írás szövegfájlba. | Útmutató: Szöveg írása fájlba |
| Olvasás szövegfájlból. | Útmutató: Szöveg beolvasása fájlból |
| Szöveg hozzáfűzése egy fájlhoz. |
Útmutató: Naplófájl megnyitása és hozzáfűzése File.AppendText FileInfo.AppendText |
| Fájl méretének lekérése. | FileInfo.Length |
| A fájl attribútumainak lekérése. | File.GetAttributes |
| Adja meg egy fájl attribútumait. | File.SetAttributes |
| Állapítsa meg, hogy létezik-e fájl. | File.Exists |
| Olvasás bináris fájlból. | Útmutató: Olvasás és írás újonnan létrehozott adatfájlba |
| Írás bináris fájlba. | Útmutató: Olvasás és írás újonnan létrehozott adatfájlba |
Lásd még
A következőre érvényes:
Write(Int16)
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Kétbájtos aláírt egész számot ír az aktuális streambe, és két bájttal előrelépteti a stream pozícióját.
public:
virtual void Write(short value);
public virtual void Write(short value);
abstract member Write : int16 -> unit
override this.Write : int16 -> unit
Public Overridable Sub Write (value As Short)
Paraméterek
- value
- Int16
Az írandó két bájtos aláírt egész szám.
Kivételek
I/O-hiba történik.
A stream bezárult.
Megjegyzések
BinaryWriter ezt az adattípust kis endian formátumban tárolja.
Az alábbi táblázat más tipikus vagy kapcsolódó I/O-feladatokra mutat be példákat.
| Ehhez... | Tekintse meg a jelen témakörben szereplő példát... |
|---|---|
| Szövegfájl létrehozása. | Útmutató: Szöveg írása fájlba |
| Írás szövegfájlba. | Útmutató: Szöveg írása fájlba |
| Olvasás szövegfájlból. | Útmutató: Szöveg beolvasása fájlból |
| Szöveg hozzáfűzése egy fájlhoz. |
Útmutató: Naplófájl megnyitása és hozzáfűzése File.AppendText FileInfo.AppendText |
| Fájl méretének lekérése. | FileInfo.Length |
| A fájl attribútumainak lekérése. | File.GetAttributes |
| Adja meg egy fájl attribútumait. | File.SetAttributes |
| Állapítsa meg, hogy létezik-e fájl. | File.Exists |
| Olvasás bináris fájlból. | Útmutató: Olvasás és írás újonnan létrehozott adatfájlba |
| Írás bináris fájlba. | Útmutató: Olvasás és írás újonnan létrehozott adatfájlba |
Lásd még
A következőre érvényes:
Write(Half)
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Kétbájtos lebegőpontos értéket ír az aktuális adatfolyamba, és két bájttal lép előre a stream pozícióján.
public:
virtual void Write(Half value);
public virtual void Write(Half value);
abstract member Write : Half -> unit
override this.Write : Half -> unit
Public Overridable Sub Write (value As Half)
Paraméterek
- value
- Half
Az írandó két bájtos lebegőpontos érték.
Kivételek
I/O-hiba történik.
A stream bezárult.
Példák
Az alábbi példakód bemutatja, hogyan olvashat és írhat Double adatokat a memóriába az BinaryReader osztály tetején BinaryWriter lévő és MemoryStream az osztályokkal.
MemoryStream csak adatokat olvas és ír Byte .
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
Megjegyzések
A gyakori I/O-feladatok listáját a Gyakori I/O-feladatok című témakörben találja.
Lásd még
A következőre érvényes:
Write(Double)
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Nyolcbájtos lebegőpontos értéket ír az aktuális streambe, és nyolc bájttal lép előre a stream pozícióján.
public:
virtual void Write(double value);
public virtual void Write(double value);
abstract member Write : double -> unit
override this.Write : double -> unit
Public Overridable Sub Write (value As Double)
Paraméterek
- value
- Double
Az írandó nyolc bájtos lebegőpontos érték.
Kivételek
I/O-hiba történik.
A stream bezárult.
Példák
Az alábbi példakód bemutatja, hogyan olvashat és írhat Double adatokat a memóriába az BinaryReader osztály tetején BinaryWriter lévő és MemoryStream az osztályokkal.
MemoryStream csak adatokat olvas és ír Byte .
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
Megjegyzések
A gyakori I/O-feladatok listáját a Gyakori I/O-feladatok című témakörben találja.
Lásd még
A következőre érvényes:
Write(Decimal)
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Decimális értéket ír az aktuális adatfolyamra, és tizenhat bájttal lép előre a stream pozícióján.
public:
virtual void Write(System::Decimal value);
public virtual void Write(decimal value);
abstract member Write : decimal -> unit
override this.Write : decimal -> unit
Public Overridable Sub Write (value As Decimal)
Paraméterek
- value
- Decimal
Az írandó decimális érték.
Kivételek
I/O-hiba történik.
A stream bezárult.
Megjegyzések
Az alábbi táblázat más tipikus vagy kapcsolódó I/O-feladatokra mutat be példákat.
| Ehhez... | Tekintse meg a jelen témakörben szereplő példát... |
|---|---|
| Szövegfájl létrehozása. | Útmutató: Szöveg írása fájlba |
| Írás szövegfájlba. | Útmutató: Szöveg írása fájlba |
| Olvasás szövegfájlból. | Útmutató: Szöveg beolvasása fájlból |
| Szöveg hozzáfűzése egy fájlhoz. |
Útmutató: Naplófájl megnyitása és hozzáfűzése File.AppendText FileInfo.AppendText |
| Fájl méretének lekérése. | FileInfo.Length |
| A fájl attribútumainak lekérése. | File.GetAttributes |
| Adja meg egy fájl attribútumait. | File.SetAttributes |
| Állapítsa meg, hogy létezik-e fájl. | File.Exists |
| Olvasás bináris fájlból. | Útmutató: Olvasás és írás újonnan létrehozott adatfájlba |
| Írás bináris fájlba. | Útmutató: Olvasás és írás újonnan létrehozott adatfájlba |
Lásd még
A következőre érvényes:
Write(Char)
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Unicode-karaktert ír az aktuális streambe, és a használt és a streambe írt konkrét karaktereknek Encoding megfelelően alakítja tovább a stream aktuális pozícióját.
public:
virtual void Write(char ch);
public virtual void Write(char ch);
abstract member Write : char -> unit
override this.Write : char -> unit
Public Overridable Sub Write (ch As Char)
Paraméterek
- ch
- Char
A nem helyettesítő, Unicode karaktert írni.
Kivételek
I/O-hiba történik.
A stream bezárult.
ch egyetlen helyettesítő karakter.
Példák
Az alábbi példakód bemutatja, hogyan olvashat és írhat adatokat memória használatával háttértárként.
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
Megjegyzések
Adatformázási ütközések miatt nem ajánlott ezt a metódust a következő kódolásokkal használni:
UTF-7
ISO-2022-JP
ISCII
A gyakori I/O-feladatok listáját a Gyakori I/O-feladatok című témakörben találja.
A Unicode helyettesítő karaktereket párként kell kiírni ugyanabban a hívásban, nem egyenként. Ha támogatást igényel a helyettesítő párokhoz az alkalmazásban, fontolja meg egy karaktertömb használatát és a metódus túlterhelését Write .
Lásd még
A következőre érvényes:
Write(Byte[])
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Bájttömböt ír a mögöttes adatfolyamba.
public:
virtual void Write(cli::array <System::Byte> ^ buffer);
public virtual void Write(byte[] buffer);
abstract member Write : byte[] -> unit
override this.Write : byte[] -> unit
Public Overridable Sub Write (buffer As Byte())
Paraméterek
- buffer
- Byte[]
Az írandó adatokat tartalmazó bájttömb.
Kivételek
I/O-hiba történik.
A stream bezárult.
buffer az null.
Példák
Az alábbi példakód bemutatja, hogyan írhat bináris adatokat memória használatával háttértárként, majd ellenőrizheti, hogy az adatok helyesen írták-e.
using System;
using System.IO;
class BinaryRW
{
static void Main()
{
const int arrayLength = 1000;
// Create random data to write to the stream.
byte[] dataArray = new byte[arrayLength];
new Random().NextBytes(dataArray);
BinaryWriter binWriter = new BinaryWriter(new MemoryStream());
// Write the data to the stream.
Console.WriteLine("Writing the data.");
binWriter.Write(dataArray);
// Create the reader using the stream from the writer.
BinaryReader binReader =
new BinaryReader(binWriter.BaseStream);
// Set Position to the beginning of the stream.
binReader.BaseStream.Position = 0;
// Read and verify the data.
byte[] verifyArray = binReader.ReadBytes(arrayLength);
if(verifyArray.Length != arrayLength)
{
Console.WriteLine("Error writing the data.");
return;
}
for(int i = 0; i < arrayLength; i++)
{
if(verifyArray[i] != dataArray[i])
{
Console.WriteLine("Error writing the data.");
return;
}
}
Console.WriteLine("The data was written and verified.");
}
}
open System
open System.IO
let arrayLength = 1000
// Create random data to write to the stream.
let dataArray = Array.zeroCreate<byte> arrayLength
Random().NextBytes dataArray
let binWriter = new BinaryWriter(new MemoryStream())
// Write the data to the stream.ch
printfn "Writing the data."
binWriter.Write dataArray
// Create the reader using the stream from the writer.
let binReader = new BinaryReader(binWriter.BaseStream)
// Set Position to the beginning of the stream.
binReader.BaseStream.Position <- 0
// Read and verify the data.
let verifyArray = binReader.ReadBytes arrayLength
if verifyArray.Length <> arrayLength then
printfn "Error writing the data."
else
let mutable failed = false
for i = 0 to arrayLength - 1 do
if verifyArray[i] <> dataArray[i] then
printfn "Error writing the data."
failed <- true
if not failed then
printfn "The data was written and verified."
Imports System.IO
Public Class BinaryRW
Shared Sub Main()
Const upperBound As Integer = 1000
' Create random data to write to the stream.
Dim dataArray(upperBound) As Byte
Dim randomGenerator As New Random
randomGenerator.NextBytes(dataArray)
Dim binWriter As New BinaryWriter(New MemoryStream())
' Write the data to the stream.
Console.WriteLine("Writing the data.")
binWriter.Write(dataArray)
' Create the reader using the stream from the writer.
Dim binReader As New BinaryReader(binWriter.BaseStream)
' Set the stream position to the beginning of the stream.
binReader.BaseStream.Position = 0
' Read and verify the data.
Dim verifyArray() As Byte = _
binReader.ReadBytes(dataArray.Length)
If verifyArray.Length <> dataArray.Length Then
Console.WriteLine("Error writing the data.")
Return
End If
For i As Integer = 0 To upperBound
If verifyArray(i) <> dataArray(i) Then
Console.WriteLine("Error writing the data.")
Return
End If
Next i
Console.WriteLine("The data was written and verified.")
End Sub
End Class
Megjegyzések
A gyakori I/O-feladatok listáját a Gyakori I/O-feladatok című témakörben találja.
Lásd még
A következőre érvényes:
Write(Byte)
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Aláíratlan bájtot ír az aktuális adatfolyamra, és egy bájttal előrelépteti a stream pozícióját.
public:
virtual void Write(System::Byte value);
public virtual void Write(byte value);
abstract member Write : byte -> unit
override this.Write : byte -> unit
Public Overridable Sub Write (value As Byte)
Paraméterek
- value
- Byte
Az írandó aláíratlan bájt.
Kivételek
I/O-hiba történik.
A stream bezárult.
Példák
Az alábbi példakód bemutatja, hogyan írhat bináris adatokat memória használatával háttértárként, majd ellenőrizheti, hogy az adatok helyesen írták-e.
using System;
using System.IO;
class BinaryRW
{
static void Main()
{
int i = 0;
// Create random data to write to the stream.
byte[] writeArray = new byte[1000];
new Random().NextBytes(writeArray);
BinaryWriter binWriter = new BinaryWriter(new MemoryStream());
BinaryReader binReader =
new BinaryReader(binWriter.BaseStream);
try
{
// Write the data to the stream.
Console.WriteLine("Writing the data.");
for(i = 0; i < writeArray.Length; i++)
{
binWriter.Write(writeArray[i]);
}
// Set the stream position to the beginning of the stream.
binReader.BaseStream.Position = 0;
// Read and verify the data from the stream.
for(i = 0; i < writeArray.Length; i++)
{
if(binReader.ReadByte() != writeArray[i])
{
Console.WriteLine("Error writing the data.");
return;
}
}
Console.WriteLine("The data was written and verified.");
}
// Catch the EndOfStreamException and write an error message.
catch(EndOfStreamException e)
{
Console.WriteLine("Error writing the data.\n{0}",
e.GetType().Name);
}
}
}
open System
open System.IO
// Create random data to write to the stream.
let writeArray = Array.zeroCreate<byte> 1000
Random().NextBytes writeArray
let binWriter = new BinaryWriter(new MemoryStream())
let binReader = new BinaryReader(binWriter.BaseStream)
try
// Write the data to the stream.
printfn "Writing the data."
for i = 0 to writeArray.Length - 1 do
binWriter.Write writeArray[i]
// Set the stream position to the beginning of the stream.
binReader.BaseStream.Position <- 0
let mutable failed = false
// Read and verify the data from the stream.
for i = 0 to writeArray.Length - 1 do
if binReader.ReadByte() <> writeArray[i] then
printfn "Error writing the data."
failed <- true
if not failed then
printfn "The data was written and verified."
// Catch the EndOfStreamException and write an error message.
with :? EndOfStreamException as e ->
printfn $"Error writing the data.\n{e.GetType().Name}"
Imports System.IO
Public Class BinaryRW
Shared Sub Main()
Dim i As Integer = 0
' Create random data to write to the stream.
Dim writeArray(1000) As Byte
Dim randomGenerator As New Random()
randomGenerator.NextBytes(writeArray)
Dim binWriter As New BinaryWriter(New MemoryStream())
Dim binReader As New BinaryReader(binWriter.BaseStream)
Try
' Write the data to the stream.
Console.WriteLine("Writing the data.")
For i = 0 To writeArray.Length - 1
binWriter.Write(writeArray(i))
Next i
' Set the stream position to the beginning of the stream.
binReader.BaseStream.Position = 0
' Read and verify the data from the stream.
For i = 0 To writeArray.Length - 1
If binReader.ReadByte() <> writeArray(i) Then
Console.WriteLine("Error writing the data.")
Return
End If
Next i
Console.WriteLine("The data was written and verified.")
' Catch the EndOfStreamException and write an error message.
Catch ex As EndOfStreamException
Console.WriteLine("Error writing the data: {0}", _
ex.GetType().Name)
End Try
End Sub
End Class
Megjegyzések
Adatformázási ütközések miatt nem ajánlott ezt a metódust a következő kódolásokkal használni:
UTF-7
ISO-2022-JP
ISCII
A gyakori I/O-feladatok listáját a Gyakori I/O-feladatok című témakörben találja.
Lásd még
A következőre érvényes:
Write(Boolean)
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Egy bájtos Boolean értéket ír az aktuális streambe, 0-val és false 1-zel.true
public:
virtual void Write(bool value);
public virtual void Write(bool value);
abstract member Write : bool -> unit
override this.Write : bool -> unit
Public Overridable Sub Write (value As Boolean)
Paraméterek
- value
- Boolean
Az Boolean írandó érték (0 vagy 1).
Kivételek
I/O-hiba történik.
A stream bezárult.
Példák
Az alábbi példakód bemutatja, hogyan tárolhatja és lekérheti az alkalmazásbeállításokat egy fájlban.
using System;
using System.IO;
using System.Text;
class ConsoleApplication
{
const string fileName = "AppSettings.dat";
static void Main()
{
WriteDefaultValues();
DisplayValues();
}
public static void WriteDefaultValues()
{
using (var stream = File.Open(fileName, FileMode.Create))
{
using (var writer = new BinaryWriter(stream, Encoding.UTF8, false))
{
writer.Write(1.250F);
writer.Write(@"c:\Temp");
writer.Write(10);
writer.Write(true);
}
}
}
public static void DisplayValues()
{
float aspectRatio;
string tempDirectory;
int autoSaveTime;
bool showStatusBar;
if (File.Exists(fileName))
{
using (var stream = File.Open(fileName, FileMode.Open))
{
using (var reader = new BinaryReader(stream, Encoding.UTF8, false))
{
aspectRatio = reader.ReadSingle();
tempDirectory = reader.ReadString();
autoSaveTime = reader.ReadInt32();
showStatusBar = reader.ReadBoolean();
}
}
Console.WriteLine("Aspect ratio set to: " + aspectRatio);
Console.WriteLine("Temp directory is: " + tempDirectory);
Console.WriteLine("Auto save time set to: " + autoSaveTime);
Console.WriteLine("Show status bar: " + showStatusBar);
}
}
}
open System.IO
open System.Text
let fileName = "AppSettings.dat"
let writeDefaultValues () =
use stream = File.Open(fileName, FileMode.Create)
use writer = new BinaryWriter(stream, Encoding.UTF8, false)
writer.Write 1.250F
writer.Write @"c:\Temp"
writer.Write 10
writer.Write true
let displayValues () =
if File.Exists fileName then
use stream = File.Open(fileName, FileMode.Open)
use reader = new BinaryReader(stream, Encoding.UTF8, false)
let aspectRatio = reader.ReadSingle()
let tempDirectory = reader.ReadString()
let autoSaveTime = reader.ReadInt32()
let showStatusBar = reader.ReadBoolean()
printfn $"Aspect ratio set to: {aspectRatio}"
printfn $"Temp directory is: {tempDirectory}"
printfn $"Auto save time set to: {autoSaveTime}"
printfn $"Show status bar: {showStatusBar}"
writeDefaultValues ()
displayValues ()
Imports System.IO
Module Module1
Const fileName As String = "AppSettings.dat"
Sub Main()
WriteDefaultValues()
DisplayValues()
End Sub
Sub WriteDefaultValues()
Using writer As BinaryWriter = New BinaryWriter(File.Open(fileName, FileMode.Create))
writer.Write(1.25F)
writer.Write("c:\Temp")
writer.Write(10)
writer.Write(True)
End Using
End Sub
Sub DisplayValues()
Dim aspectRatio As Single
Dim tempDirectory As String
Dim autoSaveTime As Integer
Dim showStatusBar As Boolean
If (File.Exists(fileName)) Then
Using reader As BinaryReader = New BinaryReader(File.Open(fileName, FileMode.Open))
aspectRatio = reader.ReadSingle()
tempDirectory = reader.ReadString()
autoSaveTime = reader.ReadInt32()
showStatusBar = reader.ReadBoolean()
End Using
Console.WriteLine("Aspect ratio set to: " & aspectRatio)
Console.WriteLine("Temp directory is: " & tempDirectory)
Console.WriteLine("Auto save time set to: " & autoSaveTime)
Console.WriteLine("Show status bar: " & showStatusBar)
End If
End Sub
End Module
Megjegyzések
A gyakori I/O-feladatok listáját a Gyakori I/O-feladatok című témakörben találja.
Lásd még
A következőre érvényes:
Write(Int32)
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
- Forrás:
- BinaryWriter.cs
Négybájtos aláírt egész számot ír az aktuális streamre, és négy bájttal előrelépteti a stream pozícióját.
public:
virtual void Write(int value);
public virtual void Write(int value);
abstract member Write : int -> unit
override this.Write : int -> unit
Public Overridable Sub Write (value As Integer)
Paraméterek
- value
- Int32
Az íráshoz a négy bájtos aláírt egész szám.
Kivételek
I/O-hiba történik.
A stream bezárult.
Példák
Az alábbi példakód bemutatja, hogyan tárolhatja és lekérheti az alkalmazásbeállításokat egy fájlban.
using System;
using System.IO;
using System.Text;
class ConsoleApplication
{
const string fileName = "AppSettings.dat";
static void Main()
{
WriteDefaultValues();
DisplayValues();
}
public static void WriteDefaultValues()
{
using (var stream = File.Open(fileName, FileMode.Create))
{
using (var writer = new BinaryWriter(stream, Encoding.UTF8, false))
{
writer.Write(1.250F);
writer.Write(@"c:\Temp");
writer.Write(10);
writer.Write(true);
}
}
}
public static void DisplayValues()
{
float aspectRatio;
string tempDirectory;
int autoSaveTime;
bool showStatusBar;
if (File.Exists(fileName))
{
using (var stream = File.Open(fileName, FileMode.Open))
{
using (var reader = new BinaryReader(stream, Encoding.UTF8, false))
{
aspectRatio = reader.ReadSingle();
tempDirectory = reader.ReadString();
autoSaveTime = reader.ReadInt32();
showStatusBar = reader.ReadBoolean();
}
}
Console.WriteLine("Aspect ratio set to: " + aspectRatio);
Console.WriteLine("Temp directory is: " + tempDirectory);
Console.WriteLine("Auto save time set to: " + autoSaveTime);
Console.WriteLine("Show status bar: " + showStatusBar);
}
}
}
open System.IO
open System.Text
let fileName = "AppSettings.dat"
let writeDefaultValues () =
use stream = File.Open(fileName, FileMode.Create)
use writer = new BinaryWriter(stream, Encoding.UTF8, false)
writer.Write 1.250F
writer.Write @"c:\Temp"
writer.Write 10
writer.Write true
let displayValues () =
if File.Exists fileName then
use stream = File.Open(fileName, FileMode.Open)
use reader = new BinaryReader(stream, Encoding.UTF8, false)
let aspectRatio = reader.ReadSingle()
let tempDirectory = reader.ReadString()
let autoSaveTime = reader.ReadInt32()
let showStatusBar = reader.ReadBoolean()
printfn $"Aspect ratio set to: {aspectRatio}"
printfn $"Temp directory is: {tempDirectory}"
printfn $"Auto save time set to: {autoSaveTime}"
printfn $"Show status bar: {showStatusBar}"
writeDefaultValues ()
displayValues ()
Imports System.IO
Module Module1
Const fileName As String = "AppSettings.dat"
Sub Main()
WriteDefaultValues()
DisplayValues()
End Sub
Sub WriteDefaultValues()
Using writer As BinaryWriter = New BinaryWriter(File.Open(fileName, FileMode.Create))
writer.Write(1.25F)
writer.Write("c:\Temp")
writer.Write(10)
writer.Write(True)
End Using
End Sub
Sub DisplayValues()
Dim aspectRatio As Single
Dim tempDirectory As String
Dim autoSaveTime As Integer
Dim showStatusBar As Boolean
If (File.Exists(fileName)) Then
Using reader As BinaryReader = New BinaryReader(File.Open(fileName, FileMode.Open))
aspectRatio = reader.ReadSingle()
tempDirectory = reader.ReadString()
autoSaveTime = reader.ReadInt32()
showStatusBar = reader.ReadBoolean()
End Using
Console.WriteLine("Aspect ratio set to: " & aspectRatio)
Console.WriteLine("Temp directory is: " & tempDirectory)
Console.WriteLine("Auto save time set to: " & autoSaveTime)
Console.WriteLine("Show status bar: " & showStatusBar)
End If
End Sub
End Module
Megjegyzések
BinaryWriter ezt az adattípust kis endian formátumban tárolja.
A gyakori I/O-feladatok listáját a Gyakori I/O-feladatok című témakörben találja.