BinaryWriter.Write Metod
Definition
Viktigt
En del information gäller för förhandsversionen av en produkt och kan komma att ändras avsevärt innan produkten blir allmänt tillgänglig. Microsoft lämnar inga garantier, uttryckliga eller underförstådda, avseende informationen som visas här.
Skriver ett värde till den aktuella strömmen.
Överlagringar
| Name | Description |
|---|---|
| Write(Char[], Int32, Int32) |
Skriver ett avsnitt av en teckenmatris till den aktuella strömmen och flyttar fram strömmens aktuella position i enlighet med de |
| Write(Byte[], Int32, Int32) |
Skriver en region för en bytematris till den aktuella strömmen. |
| Write(UInt64) |
Skriver ett osignerat heltal på åtta byte till den aktuella strömmen och avancerar strömpositionen med åtta byte. |
| Write(UInt32) |
Skriver ett osignerat heltal med fyra byte till den aktuella strömmen och avancerar strömpositionen med fyra byte. |
| Write(UInt16) |
Skriver ett osignerat heltal med två byte till den aktuella strömmen och flyttar fram strömpositionen med två byte. |
| Write(String) |
Skriver en längdprefixsträng till den här strömmen i den aktuella kodningen av BinaryWriter, och flyttar fram strömmens aktuella position i enlighet med den kodning som används och de specifika tecken som skrivs till strömmen. |
| Write(Single) |
Skriver ett flyttal med fyra byte till den aktuella strömmen och flyttar fram strömpositionen med fyra byte. |
| Write(SByte) |
Skriver en signerad byte till den aktuella strömmen och avancerar strömpositionen med en byte. |
| Write(ReadOnlySpan<Char>) |
Skriver ett teckenintervall till den aktuella strömmen och för fram strömmens aktuella position i enlighet med de |
| Write(ReadOnlySpan<Byte>) |
Skriver ett intervall med byte till den aktuella strömmen. |
| Write(Int64) |
Skriver ett åtta byte signerat heltal till den aktuella strömmen och avancerar strömpositionen med åtta byte. |
| Write(Char[]) |
Skriver en teckenmatris till den aktuella strömmen och flyttar fram strömmens aktuella position i enlighet med de |
| Write(Int16) |
Skriver ett signerat heltal med två byte till den aktuella strömmen och flyttar fram strömpositionen med två byte. |
| Write(Half) |
Skriver ett flyttal med två byte till den aktuella strömmen och flyttar fram strömpositionen med två byte. |
| Write(Double) |
Skriver ett flyttalsvärde på åtta byte till den aktuella strömmen och avancerar strömpositionen med åtta byte. |
| Write(Decimal) |
Skriver ett decimalvärde till den aktuella strömmen och ökar strömpositionen med sexton byte. |
| Write(Char) |
Skriver ett Unicode-tecken till den aktuella strömmen och för fram strömmens aktuella position i enlighet med de |
| Write(Byte[]) |
Skriver en bytematris till den underliggande strömmen. |
| Write(Byte) |
Skriver en osignerad byte till den aktuella strömmen och avancerar strömpositionen med en byte. |
| Write(Boolean) |
Skriver ett värde med en byte |
| Write(Int32) |
Skriver ett fyra byte signerat heltal till den aktuella strömmen och avancerar strömpositionen med fyra byte. |
Write(Char[], Int32, Int32)
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Skriver ett avsnitt av en teckenmatris till den aktuella strömmen och flyttar fram strömmens aktuella position i enlighet med de Encoding använda och kanske de specifika tecken som skrivs till strömmen.
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)
Parametrar
- chars
- Char[]
En teckenmatris som innehåller de data som ska skrivas.
- index
- Int32
Indexet för det första tecknet som ska läsas från chars och skriva till dataströmmen.
- count
- Int32
Antalet tecken som ska läsas från chars och skrivas till dataströmmen.
Undantag
Buffertlängden minus index är mindre än count.
chars är null.
index eller count är negativ.
Ett I/O-fel inträffar.
Strömmen är stängd.
Exempel
Följande kodexempel visar hur du läser och skriver data med hjälp av minne som ett lagringsplats för säkerhetskopiering.
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
Kommentarer
En lista över vanliga I/O-uppgifter finns i Vanliga I/O-uppgifter.
Se även
Gäller för
Write(Byte[], Int32, Int32)
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Skriver en region för en bytematris till den aktuella strömmen.
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)
Parametrar
- buffer
- Byte[]
En bytematris som innehåller de data som ska skrivas.
- index
- Int32
Indexet för den första byte som ska läsas från buffer och skriva till dataströmmen.
- count
- Int32
Antalet byte som ska läsas från buffer och skrivas till strömmen.
Undantag
Buffertlängden minus index är mindre än count.
buffer är null.
index eller count är negativ.
Ett I/O-fel inträffar.
Strömmen är stängd.
Exempel
I följande kodexempel visas hur du skriver binära data med hjälp av minne som ett lagringslager och sedan kontrollerar att data har skrivits korrekt.
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
Kommentarer
En lista över vanliga I/O-uppgifter finns i Vanliga I/O-uppgifter.
Se även
Gäller för
Write(UInt64)
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Viktigt!
Detta API uppfyller inte CLS.
Skriver ett osignerat heltal på åtta byte till den aktuella strömmen och avancerar strömpositionen med åtta byte.
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)
Parametrar
- value
- UInt64
Det osignerade heltal med åtta byte som ska skrivas.
- Attribut
Undantag
Ett I/O-fel inträffar.
Strömmen är stängd.
Kommentarer
BinaryWriter lagrar den här datatypen i lite endianskt format.
En lista över vanliga I/O-uppgifter finns i Vanliga I/O-uppgifter.
Se även
Gäller för
Write(UInt32)
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Viktigt!
Detta API uppfyller inte CLS.
Skriver ett osignerat heltal med fyra byte till den aktuella strömmen och avancerar strömpositionen med fyra byte.
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)
Parametrar
- value
- UInt32
Det osignerade heltal med fyra byte som ska skrivas.
- Attribut
Undantag
Ett I/O-fel inträffar.
Strömmen är stängd.
Kommentarer
BinaryWriter lagrar den här datatypen i lite endianskt format.
En lista över vanliga I/O-uppgifter finns i Vanliga I/O-uppgifter.
Se även
Gäller för
Write(UInt16)
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Viktigt!
Detta API uppfyller inte CLS.
Skriver ett osignerat heltal med två byte till den aktuella strömmen och flyttar fram strömpositionen med två byte.
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)
Parametrar
- value
- UInt16
Det osignerade heltal med två byte som ska skrivas.
- Attribut
Undantag
Ett I/O-fel inträffar.
Strömmen är stängd.
Kommentarer
BinaryWriter lagrar den här datatypen i lite endianskt format.
En lista över vanliga I/O-uppgifter finns i Vanliga I/O-uppgifter.
Se även
Gäller för
Write(String)
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Skriver en längdprefixsträng till den här strömmen i den aktuella kodningen av BinaryWriter, och flyttar fram strömmens aktuella position i enlighet med den kodning som används och de specifika tecken som skrivs till strömmen.
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)
Parametrar
- value
- String
Värdet som ska skrivas.
Undantag
Ett I/O-fel inträffar.
value är null.
Strömmen är stängd.
Exempel
Följande kodexempel visar hur du lagrar och hämtar programinställningar i en fil.
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
Kommentarer
Längdprefix innebär att den här metoden först skriver längden på strängen, i byte, när den kodas med instansens BinaryWriter aktuella kodning till strömmen. Det här värdet skrivs som ett osignerat heltal. Den här metoden skriver sedan så många byte till strömmen.
Strängen "A" har till exempel en längd på 1, men när den kodas med UTF-16; längden är 2 byte, så värdet som skrivs i prefixet är 2 och 3 byte skrivs till strömmen, inklusive prefixet.
En lista över vanliga I/O-uppgifter finns i Vanliga I/O-uppgifter.
Se även
Gäller för
Write(Single)
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Skriver ett flyttal med fyra byte till den aktuella strömmen och flyttar fram strömpositionen med fyra byte.
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)
Parametrar
- value
- Single
Värdet för flyttal med fyra byte som ska skrivas.
Undantag
Ett I/O-fel inträffar.
Strömmen är stängd.
Exempel
Följande kodexempel visar hur du lagrar och hämtar programinställningar i en fil.
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
Kommentarer
BinaryWriter lagrar den här datatypen i lite endianskt format.
En lista över vanliga I/O-uppgifter finns i Vanliga I/O-uppgifter.
Se även
Gäller för
Write(SByte)
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Viktigt!
Detta API uppfyller inte CLS.
Skriver en signerad byte till den aktuella strömmen och avancerar strömpositionen med en byte.
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)
Parametrar
- value
- SByte
Den signerade byte som ska skrivas.
- Attribut
Undantag
Ett I/O-fel inträffar.
Strömmen är stängd.
Kommentarer
En lista över vanliga I/O-uppgifter finns i Vanliga I/O-uppgifter.
Se även
Gäller för
Write(ReadOnlySpan<Char>)
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Skriver ett teckenintervall till den aktuella strömmen och för fram strömmens aktuella position i enlighet med de Encoding använda och kanske de specifika tecken som skrivs till strömmen.
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))
Parametrar
- chars
- ReadOnlySpan<Char>
Ett intervall med tecken att skriva.
Gäller för
Write(ReadOnlySpan<Byte>)
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Skriver ett intervall med byte till den aktuella strömmen.
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))
Parametrar
- buffer
- ReadOnlySpan<Byte>
Intervallet för byte som ska skrivas.
Gäller för
Write(Int64)
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Skriver ett åtta byte signerat heltal till den aktuella strömmen och avancerar strömpositionen med åtta byte.
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)
Parametrar
- value
- Int64
Det åtta bytes signerade heltal som ska skrivas.
Undantag
Ett I/O-fel inträffar.
Strömmen är stängd.
Kommentarer
BinaryWriter lagrar den här datatypen i lite endianskt format.
En lista över vanliga I/O-uppgifter finns i Vanliga I/O-uppgifter.
Se även
Gäller för
Write(Char[])
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Skriver en teckenmatris till den aktuella strömmen och flyttar fram strömmens aktuella position i enlighet med de Encoding använda och specifika tecken som skrivs till strömmen.
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())
Parametrar
- chars
- Char[]
En teckenmatris som innehåller de data som ska skrivas.
Undantag
chars är null.
Strömmen är stängd.
Ett I/O-fel inträffar.
Exempel
Följande kodexempel visar hur du läser och skriver data med hjälp av minne som ett lagringsplats för säkerhetskopiering.
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
Kommentarer
I följande tabell visas exempel på andra typiska eller relaterade I/O-uppgifter.
| För att göra det här... | Se exemplet i det här avsnittet... |
|---|---|
| Skapa en textfil. | Anvisningar: Skriva text till en fil |
| Skriv till en textfil. | Anvisningar: Skriva text till en fil |
| Läs från en textfil. | Anvisningar: Läsa text från en fil |
| Lägg till text i en fil. |
Anvisningar: Öppna och lägg till i en loggfil File.AppendText FileInfo.AppendText |
| Hämta storleken på en fil. | FileInfo.Length |
| Hämta attributen för en fil. | File.GetAttributes |
| Ange attributen för en fil. | File.SetAttributes |
| Kontrollera om det finns en fil. | File.Exists |
| Läs från en binär fil. | Anvisningar: Läsa och skriva till en nyligen skapad datafil |
| Skriv till en binär fil. | Anvisningar: Läsa och skriva till en nyligen skapad datafil |
Se även
Gäller för
Write(Int16)
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Skriver ett signerat heltal med två byte till den aktuella strömmen och flyttar fram strömpositionen med två byte.
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)
Parametrar
- value
- Int16
Det signerade heltal med två byte som ska skrivas.
Undantag
Ett I/O-fel inträffar.
Strömmen är stängd.
Kommentarer
BinaryWriter lagrar den här datatypen i lite endianskt format.
I följande tabell visas exempel på andra typiska eller relaterade I/O-uppgifter.
| För att göra det här... | Se exemplet i det här avsnittet... |
|---|---|
| Skapa en textfil. | Anvisningar: Skriva text till en fil |
| Skriv till en textfil. | Anvisningar: Skriva text till en fil |
| Läs från en textfil. | Anvisningar: Läsa text från en fil |
| Lägg till text i en fil. |
Anvisningar: Öppna och lägg till i en loggfil File.AppendText FileInfo.AppendText |
| Hämta storleken på en fil. | FileInfo.Length |
| Hämta attributen för en fil. | File.GetAttributes |
| Ange attributen för en fil. | File.SetAttributes |
| Kontrollera om det finns en fil. | File.Exists |
| Läs från en binär fil. | Anvisningar: Läsa och skriva till en nyligen skapad datafil |
| Skriv till en binär fil. | Anvisningar: Läsa och skriva till en nyligen skapad datafil |
Se även
Gäller för
Write(Half)
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Skriver ett flyttal med två byte till den aktuella strömmen och flyttar fram strömpositionen med två byte.
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)
Parametrar
- value
- Half
Värdet för flyttal med två byte som ska skrivas.
Undantag
Ett I/O-fel inträffar.
Strömmen är stängd.
Exempel
I följande kodexempel visas hur du läser och skriver Double data till minnet med hjälp BinaryReader av klasserna och BinaryWriter ovanpå MemoryStream klassen.
MemoryStream läser och skriver Byte endast data.
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
Kommentarer
En lista över vanliga I/O-uppgifter finns i Vanliga I/O-uppgifter.
Se även
Gäller för
Write(Double)
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Skriver ett flyttalsvärde på åtta byte till den aktuella strömmen och avancerar strömpositionen med åtta byte.
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)
Parametrar
- value
- Double
Det flyttalsvärde på åtta byte som ska skrivas.
Undantag
Ett I/O-fel inträffar.
Strömmen är stängd.
Exempel
I följande kodexempel visas hur du läser och skriver Double data till minnet med hjälp BinaryReader av klasserna och BinaryWriter ovanpå MemoryStream klassen.
MemoryStream läser och skriver Byte endast data.
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
Kommentarer
En lista över vanliga I/O-uppgifter finns i Vanliga I/O-uppgifter.
Se även
Gäller för
Write(Decimal)
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Skriver ett decimalvärde till den aktuella strömmen och ökar strömpositionen med sexton byte.
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)
Parametrar
- value
- Decimal
Decimalvärdet som ska skrivas.
Undantag
Ett I/O-fel inträffar.
Strömmen är stängd.
Kommentarer
I följande tabell visas exempel på andra typiska eller relaterade I/O-uppgifter.
| För att göra det här... | Se exemplet i det här avsnittet... |
|---|---|
| Skapa en textfil. | Anvisningar: Skriva text till en fil |
| Skriv till en textfil. | Anvisningar: Skriva text till en fil |
| Läs från en textfil. | Anvisningar: Läsa text från en fil |
| Lägg till text i en fil. |
Anvisningar: Öppna och lägg till i en loggfil File.AppendText FileInfo.AppendText |
| Hämta storleken på en fil. | FileInfo.Length |
| Hämta attributen för en fil. | File.GetAttributes |
| Ange attributen för en fil. | File.SetAttributes |
| Kontrollera om det finns en fil. | File.Exists |
| Läs från en binär fil. | Anvisningar: Läsa och skriva till en nyligen skapad datafil |
| Skriv till en binär fil. | Anvisningar: Läsa och skriva till en nyligen skapad datafil |
Se även
Gäller för
Write(Char)
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Skriver ett Unicode-tecken till den aktuella strömmen och för fram strömmens aktuella position i enlighet med de Encoding använda och specifika tecken som skrivs till strömmen.
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)
Parametrar
- ch
- Char
Det icke-surrogattecken, Unicode-tecken som ska skrivas.
Undantag
Ett I/O-fel inträffar.
Strömmen är stängd.
ch är ett enskilt surrogattecken.
Exempel
Följande kodexempel visar hur du läser och skriver data med hjälp av minne som ett lagringsplats för säkerhetskopiering.
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
Kommentarer
På grund av dataformateringskonflikter rekommenderas inte användning av den här metoden med följande kodningar:
UTF-7
ISO-2022-JP
ISCII
En lista över vanliga I/O-uppgifter finns i Vanliga I/O-uppgifter.
Unicode-surrogattecken måste skrivas ut som par tillsammans i samma anrop, inte individuellt. Om du behöver stöd för surrogatpar i ditt program kan du överväga att använda en teckenmatris och Write metodens överlagring.
Se även
Gäller för
Write(Byte[])
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Skriver en bytematris till den underliggande strömmen.
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())
Parametrar
- buffer
- Byte[]
En bytematris som innehåller de data som ska skrivas.
Undantag
Ett I/O-fel inträffar.
Strömmen är stängd.
buffer är null.
Exempel
I följande kodexempel visas hur du skriver binära data med hjälp av minne som ett lagringslager och sedan kontrollerar att data har skrivits korrekt.
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
Kommentarer
En lista över vanliga I/O-uppgifter finns i Vanliga I/O-uppgifter.
Se även
Gäller för
Write(Byte)
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Skriver en osignerad byte till den aktuella strömmen och avancerar strömpositionen med en byte.
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)
Parametrar
- value
- Byte
Den osignerade byte som ska skrivas.
Undantag
Ett I/O-fel inträffar.
Strömmen är stängd.
Exempel
I följande kodexempel visas hur du skriver binära data med hjälp av minne som ett lagringslager och sedan kontrollerar att data har skrivits korrekt.
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
Kommentarer
På grund av dataformateringskonflikter rekommenderas inte användning av den här metoden med följande kodningar:
UTF-7
ISO-2022-JP
ISCII
En lista över vanliga I/O-uppgifter finns i Vanliga I/O-uppgifter.
Se även
Gäller för
Write(Boolean)
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Skriver ett värde med en byte Boolean till den aktuella strömmen, med 0 som representerar false och 1 som representerar 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)
Parametrar
- value
- Boolean
Värdet Boolean som ska skrivas (0 eller 1).
Undantag
Ett I/O-fel inträffar.
Strömmen är stängd.
Exempel
Följande kodexempel visar hur du lagrar och hämtar programinställningar i en fil.
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
Kommentarer
En lista över vanliga I/O-uppgifter finns i Vanliga I/O-uppgifter.
Se även
Gäller för
Write(Int32)
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
- Källa:
- BinaryWriter.cs
Skriver ett fyra byte signerat heltal till den aktuella strömmen och avancerar strömpositionen med fyra byte.
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)
Parametrar
- value
- Int32
Det signerade heltal med fyra byte som ska skrivas.
Undantag
Ett I/O-fel inträffar.
Strömmen är stängd.
Exempel
Följande kodexempel visar hur du lagrar och hämtar programinställningar i en fil.
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
Kommentarer
BinaryWriter lagrar den här datatypen i lite endianskt format.
En lista över vanliga I/O-uppgifter finns i Vanliga I/O-uppgifter.