BinaryWriter Klasa
Definicja
Zapisuje typy pierwotne w postaci binarnej do strumienia i obsługuje pisanie ciągów w określonym kodowaniu.Writes primitive types in binary to a stream and supports writing strings in a specific encoding.
public ref class BinaryWriter : IDisposable
public ref class BinaryWriter : IAsyncDisposable, IDisposable
public class BinaryWriter : IDisposable
public class BinaryWriter : IAsyncDisposable, IDisposable
[System.Serializable]
public class BinaryWriter : IDisposable
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class BinaryWriter : IDisposable
type BinaryWriter = class
interface IDisposable
type BinaryWriter = class
interface IAsyncDisposable
interface IDisposable
[<System.Serializable>]
type BinaryWriter = class
interface IDisposable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type BinaryWriter = class
interface IDisposable
Public Class BinaryWriter
Implements IDisposable
Public Class BinaryWriter
Implements IAsyncDisposable, IDisposable
- Dziedziczenie
-
BinaryWriter
- Atrybuty
- Implementuje
Przykłady
Poniższy przykład kodu demonstruje sposób przechowywania i pobierania ustawień aplikacji w pliku.The following code example demonstrates how to store and retrieve application settings in a file.
using System;
using System.IO;
class ConsoleApplication
{
const string fileName = "AppSettings.dat";
static void Main()
{
WriteDefaultValues();
DisplayValues();
}
public static void WriteDefaultValues()
{
using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create)))
{
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 (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
{
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);
}
}
}
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
Uwagi
BinaryWriterKlasa zawiera metody, które upraszczają zapisywanie pierwotnych typów danych do strumienia.The BinaryWriter class provides methods that simplify writing primitive data types to a stream. Na przykład można użyć Write metody do zapisania wartości logicznej do strumienia jako wartości jednobajtowej.For example, you can use the Write method to write a Boolean value to the stream as a one-byte value. Klasa obejmuje metody zapisu, które obsługują różne typy danych.The class includes write methods that support different data types.
Podczas tworzenia nowego wystąpienia BinaryWriter klasy należy podać strumień do zapisu i opcjonalnie określić typ kodowania oraz czy pozostawić strumień otwarty po usunięciu BinaryWriter obiektu.When you create a new instance of the BinaryWriter class, you provide the stream to write to, and optionally specify the type of encoding and whether to leave the stream open after disposing the BinaryWriter object. Jeśli nie określisz typu kodowania, zostanie użyty UTF-8.If you do not specify an encoding type, UTF-8 is used.
Ważne
Ten typ implementuje IDisposable interfejs.This type implements the IDisposable interface. Po zakończeniu korzystania z typu należy usunąć jego wartość bezpośrednio lub pośrednio.When you have finished using the type, you should dispose of it either directly or indirectly. Aby usunąć typ bezpośrednio, wywołaj jego Dispose metodę w try
/ catch
bloku.To dispose of the type directly, call its Dispose method in a try
/catch
block. Aby usunąć go pośrednio, użyj konstrukcji języka, takiej jak using
(w języku C#) lub Using
(w Visual Basic).To dispose of it indirectly, use a language construct such as using
(in C#) or Using
(in Visual Basic). Aby uzyskać więcej informacji, zobacz sekcję "Używanie obiektu implementującego interfejs IDisposable" w temacie dotyczącym IDisposable interfejsu.For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.
Klasa pochodna może przesłonić metody tej klasy, aby nadać unikatowe kodowanie znaków.A derived class can override the methods of this class to give unique character encodings.
Konstruktory
BinaryWriter() |
Inicjuje nowe wystąpienie BinaryWriter klasy, która zapisuje dane w strumieniu.Initializes a new instance of the BinaryWriter class that writes to a stream. |
BinaryWriter(Stream) |
Inicjuje nowe wystąpienie BinaryWriter klasy na podstawie określonego strumienia i przy użyciu kodowania UTF-8.Initializes a new instance of the BinaryWriter class based on the specified stream and using UTF-8 encoding. |
BinaryWriter(Stream, Encoding) |
Inicjuje nowe wystąpienie BinaryWriter klasy na podstawie określonego strumienia i kodowania znaków.Initializes a new instance of the BinaryWriter class based on the specified stream and character encoding. |
BinaryWriter(Stream, Encoding, Boolean) |
Inicjuje nowe wystąpienie BinaryWriter klasy na podstawie określonego strumienia i kodowania znaków, opcjonalnie pozostawiając otwarcie strumienia.Initializes a new instance of the BinaryWriter class based on the specified stream and character encoding, and optionally leaves the stream open. |
Pola
Null |
Określa BinaryWriter bez magazynu zapasowego.Specifies a BinaryWriter with no backing store. |
OutStream |
Przechowuje źródłowy strumień.Holds the underlying stream. |
Właściwości
BaseStream |
Pobiera źródłowy strumień BinaryWriter .Gets the underlying stream of the BinaryWriter. |
Metody
Close() |
Zamyka bieżący BinaryWriter i źródłowy strumień.Closes the current BinaryWriter and the underlying stream. |
Dispose() |
Zwalnia wszystkie zasoby używane przez bieżące wystąpienie klasy BinaryWriter.Releases all resources used by the current instance of the BinaryWriter class. |
Dispose(Boolean) |
Zwalnia zasoby niezarządzane używane przez element BinaryWriter i opcjonalnie zwalnia zasoby zarządzane.Releases the unmanaged resources used by the BinaryWriter and optionally releases the managed resources. |
DisposeAsync() |
Asynchronicznie zwalnia wszystkie zasoby używane przez bieżące wystąpienie BinaryWriter klasy.Asynchronously releases all resources used by the current instance of the BinaryWriter class. |
Equals(Object) |
Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.Determines whether the specified object is equal to the current object. (Odziedziczone po Object) |
Flush() |
Czyści wszystkie bufory dla bieżącego składnika zapisywania i powoduje, że wszystkie buforowane dane są zapisywane na podstawowym urządzeniu.Clears all buffers for the current writer and causes any buffered data to be written to the underlying device. |
GetHashCode() |
Służy jako domyślna funkcja skrótu.Serves as the default hash function. (Odziedziczone po Object) |
GetType() |
Pobiera Type bieżące wystąpienie.Gets the Type of the current instance. (Odziedziczone po Object) |
MemberwiseClone() |
Tworzy skróconą kopię bieżącego elementu Object .Creates a shallow copy of the current Object. (Odziedziczone po Object) |
Seek(Int32, SeekOrigin) |
Ustawia pozycję w bieżącym strumieniu.Sets the position within the current stream. |
ToString() |
Zwraca ciąg reprezentujący bieżący obiekt.Returns a string that represents the current object. (Odziedziczone po Object) |
Write(Boolean) |
Zapisuje wartość jednobajtową |
Write(Byte) |
Zapisuje bajt bez znaku w bieżącym strumieniu i przesuwa pozycję strumienia o jeden bajt.Writes an unsigned byte to the current stream and advances the stream position by one byte. |
Write(Byte[]) |
Zapisuje tablicę bajtów do źródłowego strumienia.Writes a byte array to the underlying stream. |
Write(Byte[], Int32, Int32) |
Zapisuje region tablicy bajtów w bieżącym strumieniu.Writes a region of a byte array to the current stream. |
Write(Char) |
Zapisuje znak Unicode w bieżącym strumieniu i przesuwa bieżącą pozycję strumienia zgodnie z |
Write(Char[]) |
Zapisuje tablicę znaków w bieżącym strumieniu i przesuwa bieżącą pozycję strumienia zgodnie z |
Write(Char[], Int32, Int32) |
Zapisuje sekcję tablicy znakowej do bieżącego strumienia i postępuje bieżącą pozycję strumienia zgodnie z |
Write(Decimal) |
Zapisuje wartość dziesiętną w bieżącym strumieniu i przesuwa pozycję strumienia o szesnastu bajtów.Writes a decimal value to the current stream and advances the stream position by sixteen bytes. |
Write(Double) |
Zapisuje wartość 8-bajtowej wartości zmiennoprzecinkowej w bieżącym strumieniu i przesuwa pozycję strumienia o osiem bajtów.Writes an eight-byte floating-point value to the current stream and advances the stream position by eight bytes. |
Write(Int16) |
Zapisuje liczbę całkowitą ze znakiem dwubajtowym w bieżącym strumieniu i przesuwa pozycję strumienia o dwa bajty.Writes a two-byte signed integer to the current stream and advances the stream position by two bytes. |
Write(Int32) |
Zapisuje z 4-bajtową liczbę całkowitą ze znakiem w bieżącym strumieniu i przesuwa pozycję strumienia o cztery bajty.Writes a four-byte signed integer to the current stream and advances the stream position by four bytes. |
Write(Int64) |
Zapisuje 8-bajtową liczbę całkowitą ze znakiem w bieżącym strumieniu i przesuwa pozycję strumienia o osiem bajtów.Writes an eight-byte signed integer to the current stream and advances the stream position by eight bytes. |
Write(ReadOnlySpan<Byte>) |
Zapisuje zakres bajtów do bieżącego strumienia.Writes a span of bytes to the current stream. |
Write(ReadOnlySpan<Char>) |
Zapisuje zakres znaków w bieżącym strumieniu i postępuje bieżącą pozycję strumienia zgodnie z |
Write(SByte) |
Zapisuje podpisany bajt w bieżącym strumieniu i przesuwa pozycję strumienia o jeden bajt.Writes a signed byte to the current stream and advances the stream position by one byte. |
Write(Single) |
Zapisuje wartość 4-bajtową zmiennoprzecinkową w bieżącym strumieniu i przesuwa pozycję strumienia o cztery bajty.Writes a four-byte floating-point value to the current stream and advances the stream position by four bytes. |
Write(String) |
Zapisuje ciąg poprzedzony długością do tego strumienia w bieżącym kodowaniu BinaryWriter i postępuje bieżącą pozycję strumienia zgodnie z użytym kodowaniem i określonymi znakami zapisywanych w strumieniu.Writes a length-prefixed string to this stream in the current encoding of the BinaryWriter, and advances the current position of the stream in accordance with the encoding used and the specific characters being written to the stream. |
Write(UInt16) |
Zapisuje liczbę całkowitą bez znaku dwubajtowego do bieżącego strumienia i przesuwa pozycję strumienia o dwa bajty.Writes a two-byte unsigned integer to the current stream and advances the stream position by two bytes. |
Write(UInt32) |
Zapisuje z 4-bajtową liczbę całkowitą bez znaku do bieżącego strumienia i przesuwa pozycję strumienia o cztery bajty.Writes a four-byte unsigned integer to the current stream and advances the stream position by four bytes. |
Write(UInt64) |
Zapisuje 8-bajtową liczbę całkowitą bez znaku do bieżącego strumienia i przesuwa pozycję strumienia o osiem bajtów.Writes an eight-byte unsigned integer to the current stream and advances the stream position by eight bytes. |
Write7BitEncodedInt(Int32) |
Zapisuje 32-bitową liczbę całkowitą w formacie skompresowanym.Writes a 32-bit integer in a compressed format. |
Write7BitEncodedInt64(Int64) |
Zapisuje w danym momencie numer 7 bitów.Writes out a number 7 bits at a time. |
Jawne implementacje interfejsu
IDisposable.Dispose() |
Zwalnia zasoby niezarządzane używane przez element BinaryWriter i opcjonalnie zwalnia zasoby zarządzane.Releases the unmanaged resources used by the BinaryWriter and optionally releases the managed resources. |
Metody rozszerzania
ConfigureAwait(IAsyncDisposable, Boolean) |
Określa, jak oczekują oczekiwania na zadania zwracane z asynchronicznej operacji tworzenia.Configures how awaits on the tasks returned from an async disposable are performed. |
Dotyczy
Zobacz też
- Encoding
- Instrukcje: Odczyt i zapis we właśnie utworzonym pliku danychHow to: Read and Write to a Newly Created Data File
- We/Wy plików i strumieniFile and Stream I/O
- Instrukcje: Odczytywanie tekstu z plikuHow to: Read Text from a File
- Instrukcje: Zapisywanie tekstu w plikuHow to: Write Text to a File