BinaryWriter.Write Método

Definição

Grava um valor no fluxo atual.Writes a value to the current stream.

Sobrecargas

Write(Char[], Int32, Int32)

Grava uma seção de uma matriz de caracteres no fluxo atual e avança a posição atual do fluxo de acordo com o Encoding usado e talvez com os caracteres específicos que estão sendo gravados no fluxo.Writes a section of a character array to the current stream, and advances the current position of the stream in accordance with the Encoding used and perhaps the specific characters being written to the stream.

Write(Byte[], Int32, Int32)

Grava uma região de uma matriz de bytes no fluxo atual.Writes a region of a byte array to the current stream.

Write(UInt64)

Grava um inteiro sem sinal de oito bytes no fluxo atual e avança a posição do fluxo em oito bytes.Writes an eight-byte unsigned integer to the current stream and advances the stream position by eight bytes.

Write(UInt32)

Grava um inteiro sem sinal de quatro bytes no fluxo atual e avança a posição do fluxo em quatro bytes.Writes a four-byte unsigned integer to the current stream and advances the stream position by four bytes.

Write(UInt16)

Grava um inteiro sem sinal de dois bytes no fluxo atual e avança a posição do fluxo em dois bytes.Writes a two-byte unsigned integer to the current stream and advances the stream position by two bytes.

Write(String)

Grava uma cadeia de caracteres de tamanho prefixado nesse fluxo na codificação atual do BinaryWriter e avança a posição atual do fluxo de acordo com a codificação usada e os caracteres específicos que estão sendo gravados no fluxo.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(Single)

Grava um valor de ponto flutuante de quatro bytes no fluxo atual e avança a posição do fluxo em quatro bytes.Writes a four-byte floating-point value to the current stream and advances the stream position by four bytes.

Write(SByte)

Grava um byte com sinal no fluxo atual e avança a posição do fluxo em um byte.Writes a signed byte to the current stream and advances the stream position by one byte.

Write(ReadOnlySpan<Char>)

Grava um intervalo de caracteres no fluxo atual e avança a posição atual do fluxo de acordo com a Encoding usada e talvez com os caracteres específicos que estão sendo gravados no fluxo.Writes a span of characters to the current stream, and advances the current position of the stream in accordance with the Encoding used and perhaps the specific characters being written to the stream.

Write(ReadOnlySpan<Byte>)

Grava um intervalo de bytes no fluxo atual.Writes a span of bytes to the current stream.

Write(Char)

Grava um caractere Unicode no fluxo atual e avança a posição atual do fluxo de acordo com o Encoding usado e os caracteres específicos que estão sendo gravados no fluxo.Writes a Unicode character to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream.

Write(Int32)

Grava um inteiro com sinal de quatro bytes no fluxo atual e avança a posição do fluxo em quatro bytes.Writes a four-byte signed integer to the current stream and advances the stream position by four bytes.

Write(Int16)

Grava um inteiro com sinal de dois bytes no fluxo atual e avança a posição de fluxo em dois bytes.Writes a two-byte signed integer to the current stream and advances the stream position by two bytes.

Write(Double)

Grava um valor de ponto flutuante de oito bytes no fluxo atual e avança a posição do fluxo em oito bytes.Writes an eight-byte floating-point value to the current stream and advances the stream position by eight bytes.

Write(Decimal)

Grava um valor decimal no fluxo atual e avança a posição do fluxo em 16 bytes.Writes a decimal value to the current stream and advances the stream position by sixteen bytes.

Write(Char[])

Grava uma matriz de caracteres no fluxo atual e avança a posição atual do fluxo de acordo com o Encoding usado e os caracteres específicos que estão sendo gravados no fluxo.Writes a character array to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream.

Write(Byte[])

Grava uma matriz de bytes no fluxo subjacente.Writes a byte array to the underlying stream.

Write(Byte)

Grava um byte sem sinal no fluxo atual e avança a posição do fluxo em um byte.Writes an unsigned byte to the current stream and advances the stream position by one byte.

Write(Boolean)

Grava um valor Boolean de um byte no fluxo atual, com 0 representando false e 1 representando true.Writes a one-byte Boolean value to the current stream, with 0 representing false and 1 representing true.

Write(Int64)

Grava um inteiro com sinal de oito bytes no fluxo atual e avança a posição do fluxo em oito bytes.Writes an eight-byte signed integer to the current stream and advances the stream position by eight bytes.

Write(Char[], Int32, Int32)

Grava uma seção de uma matriz de caracteres no fluxo atual e avança a posição atual do fluxo de acordo com o Encoding usado e talvez com os caracteres específicos que estão sendo gravados no fluxo.Writes a section of a character array to the current stream, and advances the current position of the stream in accordance with the Encoding used and perhaps the specific characters being written to the stream.

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)

Parâmetros

chars
Char[]

Uma matriz de caracteres que contém os dados a serem gravados.A character array containing the data to write.

index
Int32

O índice do primeiro caractere a ser lido do chars e gravado no fluxo.The index of the first character to read from chars and to write to the stream.

count
Int32

O número de caracteres a serem lidos do chars e gravados no fluxo.The number of characters to read from chars and to write to the stream.

Exceções

O tamanho do buffer menos index é menor que count.The buffer length minus index is less than count.

chars é null.chars is null.

index ou count é negativo.index or count is negative.

Ocorre um erro de E/S.An I/O error occurs.

O fluxo está fechado.The stream is closed.

Exemplos

O exemplo de código a seguir mostra como ler e gravar dados usando a memória como um repositório de backup.The following code example shows how to read and write data using memory as a backing store.

using namespace System;
using namespace System::IO;
int main()
{
   array<Char>^invalidPathChars = Path::InvalidPathChars;
   MemoryStream^ memStream = gcnew MemoryStream;
   BinaryWriter^ binWriter = gcnew 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 = gcnew BinaryReader( memStream );
   
   // Set Position to the beginning of the stream.
   binReader->BaseStream->Position = 0;
   
   // Read the data from memory and write it to the console.
   Console::Write( binReader->ReadString() );
   int arraySize = (int)(memStream->Length - memStream->Position);
   array<Char>^memoryData = gcnew array<Char>(arraySize);
   binReader->Read( memoryData, 0, arraySize );
   Console::WriteLine( memoryData );
}

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);
    }
}
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

Comentários

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Confira também

Aplica-se a

Write(Byte[], Int32, Int32)

Grava uma região de uma matriz de bytes no fluxo atual.Writes a region of a byte array to the current stream.

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)

Parâmetros

buffer
Byte[]

Uma matriz de bytes que contém os dados a serem gravados.A byte array containing the data to write.

index
Int32

O índice do primeiro byte para ler do buffer e gravar no fluxo.The index of the first byte to read from buffer and to write to the stream.

count
Int32

O número de bytes para ler do buffer e gravar no fluxo.The number of bytes to read from buffer and to write to the stream.

Exceções

O tamanho do buffer menos index é menor que count.The buffer length minus index is less than count.

buffer é null.buffer is null.

index ou count é negativo.index or count is negative.

Ocorre um erro de E/S.An I/O error occurs.

O fluxo está fechado.The stream is closed.

Exemplos

O exemplo de código a seguir mostra como gravar dados binários usando a memória como um repositório de backup e, em seguida, verificar se os dados foram gravados corretamente.The following code example shows how to write binary data using memory as a backing store, and then verify that the data was written correctly.

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.");
        }
    }
}
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

Comentários

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Aplica-se a

Write(UInt64)

Importante

Esta API não está em conformidade com CLS.

Grava um inteiro sem sinal de oito bytes no fluxo atual e avança a posição do fluxo em oito bytes.Writes an eight-byte unsigned integer to the current stream and advances the stream position by eight bytes.

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)

Parâmetros

value
UInt64

O inteiro sem sinal de oito bytes a ser gravado.The eight-byte unsigned integer to write.

Atributos

Exceções

Ocorre um erro de E/S.An I/O error occurs.

O fluxo está fechado.The stream is closed.

Comentários

BinaryWriter armazena esse tipo de dados no formato little endian.BinaryWriter stores this data type in little endian format.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Aplica-se a

Write(UInt32)

Importante

Esta API não está em conformidade com CLS.

Grava um inteiro sem sinal de quatro bytes no fluxo atual e avança a posição do fluxo em quatro bytes.Writes a four-byte unsigned integer to the current stream and advances the stream position by four bytes.

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)

Parâmetros

value
UInt32

O inteiro sem sinal de quatro bytes a ser gravado.The four-byte unsigned integer to write.

Atributos

Exceções

Ocorre um erro de E/S.An I/O error occurs.

O fluxo está fechado.The stream is closed.

Comentários

BinaryWriter armazena esse tipo de dados no formato little endian.BinaryWriter stores this data type in little endian format.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Aplica-se a

Write(UInt16)

Importante

Esta API não está em conformidade com CLS.

Grava um inteiro sem sinal de dois bytes no fluxo atual e avança a posição do fluxo em dois bytes.Writes a two-byte unsigned integer to the current stream and advances the stream position by two bytes.

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)

Parâmetros

value
UInt16

O inteiro sem sinal de dois bytes a ser gravado.The two-byte unsigned integer to write.

Atributos

Exceções

Ocorre um erro de E/S.An I/O error occurs.

O fluxo está fechado.The stream is closed.

Comentários

BinaryWriter armazena esse tipo de dados no formato little endian.BinaryWriter stores this data type in little endian format.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Aplica-se a

Write(String)

Grava uma cadeia de caracteres de tamanho prefixado nesse fluxo na codificação atual do BinaryWriter e avança a posição atual do fluxo de acordo com a codificação usada e os caracteres específicos que estão sendo gravados no fluxo.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.

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)

Parâmetros

value
String

O valor a ser gravado.The value to write.

Exceções

Ocorre um erro de E/S.An I/O error occurs.

value é null.value is null.

O fluxo está fechado.The stream is closed.

Exemplos

O exemplo de código a seguir demonstra como armazenar e recuperar configurações de aplicativo em um arquivo.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

Comentários

Comprimento-fixo significa que esse método primeiro grava o comprimento da cadeia de caracteres, em bytes, quando codificado com a BinaryWriter codificação atual da instância para o fluxo.Length-prefixed means that this method first writes the length of the string, in bytes, when encoded with the BinaryWriter instance's current encoding to the stream. Esse valor é gravado como um inteiro não assinado.This value is written as an unsigned integer. Esse método grava muitos bytes no fluxo.This method then writes that many bytes to the stream.

Por exemplo, a cadeia de caracteres "A" tem um comprimento de 1, mas quando codificada com UTF-16; o comprimento é 2 bytes, portanto, o valor escrito no prefixo é 2 e 3 bytes são gravados no fluxo, incluindo o prefixo.For example, the string "A" has a length of 1, but when encoded with UTF-16; the length is 2 bytes, so the value written in the prefix is 2, and 3 bytes are written to the stream, including the prefix.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Confira também

Aplica-se a

Write(Single)

Grava um valor de ponto flutuante de quatro bytes no fluxo atual e avança a posição do fluxo em quatro bytes.Writes a four-byte floating-point value to the current stream and advances the stream position by four bytes.

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)

Parâmetros

value
Single

O valor de ponto flutuante de quatro bytes a ser gravado.The four-byte floating-point value to write.

Exceções

Ocorre um erro de E/S.An I/O error occurs.

O fluxo está fechado.The stream is closed.

Exemplos

O exemplo de código a seguir demonstra como armazenar e recuperar configurações de aplicativo em um arquivo.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

Comentários

BinaryWriter armazena esse tipo de dados no formato little endian.BinaryWriter stores this data type in little endian format.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Aplica-se a

Write(SByte)

Importante

Esta API não está em conformidade com CLS.

Grava um byte com sinal no fluxo atual e avança a posição do fluxo em um byte.Writes a signed byte to the current stream and advances the stream position by one 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)

Parâmetros

value
SByte

O byte com sinal a ser gravado.The signed byte to write.

Atributos

Exceções

Ocorre um erro de E/S.An I/O error occurs.

O fluxo está fechado.The stream is closed.

Comentários

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Aplica-se a

Write(ReadOnlySpan<Char>)

Grava um intervalo de caracteres no fluxo atual e avança a posição atual do fluxo de acordo com a Encoding usada e talvez com os caracteres específicos que estão sendo gravados no fluxo.Writes a span of characters to the current stream, and advances the current position of the stream in accordance with the Encoding used and perhaps the specific characters being written to the stream.

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))

Parâmetros

chars
ReadOnlySpan<Char>

Um intervalo de char a ser gravado.A span of chars to write.

Aplica-se a

Write(ReadOnlySpan<Byte>)

Grava um intervalo de bytes no fluxo atual.Writes a span of bytes to the current stream.

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))

Parâmetros

buffer
ReadOnlySpan<Byte>

O intervalo de bytes a ser gravado.The span of bytes to write.

Aplica-se a

Write(Char)

Grava um caractere Unicode no fluxo atual e avança a posição atual do fluxo de acordo com o Encoding usado e os caracteres específicos que estão sendo gravados no fluxo.Writes a Unicode character to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream.

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)

Parâmetros

ch
Char

O caractere Unicode não alternativo a ser gravado.The non-surrogate, Unicode character to write.

Exceções

Ocorre um erro de E/S.An I/O error occurs.

O fluxo está fechado.The stream is closed.

ch é um caractere alternativo único.ch is a single surrogate character.

Exemplos

O exemplo de código a seguir mostra como ler e gravar dados usando a memória como um repositório de backup.The following code example shows how to read and write data using memory as a backing store.

using namespace System;
using namespace System::IO;
int main()
{
   int i;
   array<Char>^invalidPathChars = Path::InvalidPathChars;
   MemoryStream^ memStream = gcnew MemoryStream;
   BinaryWriter^ binWriter = gcnew 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 = gcnew BinaryReader( memStream );
   
   // Set Position to the beginning of the stream.
   binReader->BaseStream->Position = 0;
   
   // Read the data from memory and write it to the console.
   Console::Write( binReader->ReadString() );
   array<Char>^memoryData = gcnew array<Char>(memStream->Length - memStream->Position);
   for ( i = 0; i < memoryData->Length; i++ )
   {
      memoryData[ i ] = binReader->ReadChar();

   }
   Console::WriteLine( memoryData );
}

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);
    }
}
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

Comentários

Devido a conflitos de formatação de dados, não é recomendável usar este método com as seguintes codificações:Because of data formatting conflicts, using this method with the following encodings is not recommended:

  • UTF-7UTF-7

  • ISO-2022-JPISO-2022-JP

  • ISCIIISCII

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Caracteres substitutos Unicode devem ser gravados como pares na mesma chamada, não individualmente.Unicode surrogate characters must be written out as pairs together in the same call, not individually. Se você precisar de suporte para pares substitutos em seu aplicativo, considere usar uma matriz de caracteres e a Write sobrecarga do método.If you require support for surrogate pairs in your application, consider using a character array and the Write method overload.

Confira também

Aplica-se a

Write(Int32)

Grava um inteiro com sinal de quatro bytes no fluxo atual e avança a posição do fluxo em quatro bytes.Writes a four-byte signed integer to the current stream and advances the stream position by four bytes.

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)

Parâmetros

value
Int32

O inteiro com sinal de quatro bytes a ser gravado.The four-byte signed integer to write.

Exceções

Ocorre um erro de E/S.An I/O error occurs.

O fluxo está fechado.The stream is closed.

Exemplos

O exemplo de código a seguir demonstra como armazenar e recuperar configurações de aplicativo em um arquivo.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

Comentários

BinaryWriter armazena esse tipo de dados no formato little endian.BinaryWriter stores this data type in little endian format.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Aplica-se a

Write(Int16)

Grava um inteiro com sinal de dois bytes no fluxo atual e avança a posição de fluxo em dois bytes.Writes a two-byte signed integer to the current stream and advances the stream position by two bytes.

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)

Parâmetros

value
Int16

O inteiro com sinal de dois bytes a ser gravado.The two-byte signed integer to write.

Exceções

Ocorre um erro de E/S.An I/O error occurs.

O fluxo está fechado.The stream is closed.

Comentários

BinaryWriter armazena esse tipo de dados no formato little endian.BinaryWriter stores this data type in little endian format.

A tabela a seguir lista exemplos de outras tarefas de e/s típicas ou relacionadas.The following table lists examples of other typical or related I/O tasks.

Para fazer isso...To do this... Veja o exemplo neste tópico...See the example in this topic...
Crie um arquivo de texto.Create a text file. Como gravar texto em um arquivoHow to: Write Text to a File
Gravar em um arquivo de texto.Write to a text file. Como gravar texto em um arquivoHow to: Write Text to a File
Ler de um arquivo de texto.Read from a text file. Como ler texto de um arquivoHow to: Read Text from a File
Acrescentar texto a um arquivo.Append text to a file. Como abrir e acrescentar a um arquivo de logHow to: Open and Append to a Log File

File.AppendText

FileInfo.AppendText
Obter o tamanho de um arquivo.Get the size of a file. FileInfo.Length
Obter os atributos de um arquivo.Get the attributes of a file. File.GetAttributes
Defina os atributos de um arquivo.Set the attributes of a file. File.SetAttributes
Determine se um arquivo existe.Determine if a file exists. File.Exists
Ler de um arquivo binário.Read from a binary file. Como ler e gravar em um arquivo de dados recém-criadoHow to: Read and Write to a Newly Created Data File
Gravar em um arquivo binário.Write to a binary file. Como ler e gravar em um arquivo de dados recém-criadoHow to: Read and Write to a Newly Created Data File

Aplica-se a

Write(Double)

Grava um valor de ponto flutuante de oito bytes no fluxo atual e avança a posição do fluxo em oito bytes.Writes an eight-byte floating-point value to the current stream and advances the stream position by eight bytes.

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)

Parâmetros

value
Double

O valor de ponto flutuante de oito bytes a ser gravado.The eight-byte floating-point value to write.

Exceções

Ocorre um erro de E/S.An I/O error occurs.

O fluxo está fechado.The stream is closed.

Exemplos

O exemplo de código a seguir mostra como ler e gravar Double dados na memória usando as BinaryReader BinaryWriter classes e no topo da MemoryStream classe.The following code example shows how to read and write Double data to memory by using the BinaryReader and BinaryWriter classes on top of the MemoryStream class. MemoryStream somente lê e grava Byte dados.MemoryStream only reads and writes Byte data.

using namespace System;
using namespace System::IO;
int main()
{
   int i;
   const int arrayLength = 1000;
   
   // Create random data to write to the stream.
   array<double>^dataArray = gcnew array<double>(arrayLength);
   Random^ randomGenerator = gcnew Random;
   for ( i = 0; i < arrayLength; i++ )
   {
      dataArray[ i ] = 100.1 * randomGenerator->NextDouble();

   }
   BinaryWriter^ binWriter = gcnew BinaryWriter( gcnew MemoryStream );
   try
   {
      
      // Write data to the stream.
      Console::WriteLine( "Writing data to the stream." );
      i = 0;
      for ( i = 0; i < arrayLength; i++ )
      {
         binWriter->Write( dataArray[ i ] );

      }
      
      // Create a reader using the stream from the writer.
      BinaryReader^ binReader = gcnew BinaryReader( binWriter->BaseStream );
      
      // Return to the beginning of the stream.
      binReader->BaseStream->Position = 0;
      try
      {
         
         // Read and verify the data.
         i = 0;
         Console::WriteLine( "Verifying the written data." );
         for ( i = 0; i < arrayLength; i++ )
         {
            if ( binReader->ReadDouble() != dataArray[ i ] )
            {
               Console::WriteLine( "Error writing data." );
               break;
            }

         }
         Console::WriteLine( "The data was written and verified." );
      }
      catch ( EndOfStreamException^ e ) 
      {
         Console::WriteLine( "Error writing data: {0}.", e->GetType()->Name );
      }

   }
   finally
   {
      binWriter->Close();
   }

}

using System;
using System.IO;

class BinaryRW
{
    static void Main()
    {
        int i;
        const int arrayLength = 1000;

        // Create random data to write to the stream.
        Random randomGenerator = new Random();
        double[] dataArray = new double[arrayLength];
        for(i = 0; i < arrayLength; i++)
        {
            dataArray[i] = 100.1 * randomGenerator.NextDouble();
        }

        using(BinaryWriter binWriter =
            new BinaryWriter(new MemoryStream()))
        {
            // Write the data to the stream.
            Console.WriteLine("Writing data to the stream.");
            for(i = 0; i < arrayLength; i++)
            {
                binWriter.Write(dataArray[i]);
            }

            // Create a reader using the stream from the writer.
            using(BinaryReader binReader =
                new BinaryReader(binWriter.BaseStream))
            {
                try
                {
                    // Return to the beginning of the stream.
                    binReader.BaseStream.Position = 0;

                    // Read and verify the data.
                    Console.WriteLine("Verifying the written data.");
                    for(i = 0; i < arrayLength; i++)
                    {
                        if(binReader.ReadDouble() != dataArray[i])
                        {
                            Console.WriteLine("Error writing data.");
                            break;
                        }
                    }
                    Console.WriteLine("The data was written " +
                        "and verified.");
                }
                catch(EndOfStreamException e)
                {
                    Console.WriteLine("Error writing data: {0}.",
                        e.GetType().Name);
                }
            }
        }
    }
}
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

Comentários

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Aplica-se a

Write(Decimal)

Grava um valor decimal no fluxo atual e avança a posição do fluxo em 16 bytes.Writes a decimal value to the current stream and advances the stream position by sixteen bytes.

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)

Parâmetros

value
Decimal

O valor decimal a ser gravado.The decimal value to write.

Exceções

Ocorre um erro de E/S.An I/O error occurs.

O fluxo está fechado.The stream is closed.

Comentários

A tabela a seguir lista exemplos de outras tarefas de e/s típicas ou relacionadas.The following table lists examples of other typical or related I/O tasks.

Para fazer isso...To do this... Veja o exemplo neste tópico...See the example in this topic...
Crie um arquivo de texto.Create a text file. Como gravar texto em um arquivoHow to: Write Text to a File
Gravar em um arquivo de texto.Write to a text file. Como gravar texto em um arquivoHow to: Write Text to a File
Ler de um arquivo de texto.Read from a text file. Como ler texto de um arquivoHow to: Read Text from a File
Acrescentar texto a um arquivo.Append text to a file. Como abrir e acrescentar a um arquivo de logHow to: Open and Append to a Log File

File.AppendText

FileInfo.AppendText
Obter o tamanho de um arquivo.Get the size of a file. FileInfo.Length
Obter os atributos de um arquivo.Get the attributes of a file. File.GetAttributes
Defina os atributos de um arquivo.Set the attributes of a file. File.SetAttributes
Determine se um arquivo existe.Determine if a file exists. File.Exists
Ler de um arquivo binário.Read from a binary file. Como ler e gravar em um arquivo de dados recém-criadoHow to: Read and Write to a Newly Created Data File
Gravar em um arquivo binário.Write to a binary file. Como ler e gravar em um arquivo de dados recém-criadoHow to: Read and Write to a Newly Created Data File

Aplica-se a

Write(Char[])

Grava uma matriz de caracteres no fluxo atual e avança a posição atual do fluxo de acordo com o Encoding usado e os caracteres específicos que estão sendo gravados no fluxo.Writes a character array to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream.

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())

Parâmetros

chars
Char[]

Uma matriz de caracteres que contém os dados a serem gravados.A character array containing the data to write.

Exceções

chars é null.chars is null.

O fluxo está fechado.The stream is closed.

Ocorre um erro de E/S.An I/O error occurs.

Exemplos

O exemplo de código a seguir mostra como ler e gravar dados usando a memória como um repositório de backup.The following code example shows how to read and write data using memory as a backing store.

using namespace System;
using namespace System::IO;
int main()
{
   array<Char>^invalidPathChars = Path::InvalidPathChars;
   MemoryStream^ memStream = gcnew MemoryStream;
   BinaryWriter^ binWriter = gcnew 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 = gcnew BinaryReader( memStream );
   
   // Set Position to the beginning of the stream.
   binReader->BaseStream->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) ) );
}

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)));
    }
}
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

Comentários

A tabela a seguir lista exemplos de outras tarefas de e/s típicas ou relacionadas.The following table lists examples of other typical or related I/O tasks.

Para fazer isso...To do this... Veja o exemplo neste tópico...See the example in this topic...
Crie um arquivo de texto.Create a text file. Como gravar texto em um arquivoHow to: Write Text to a File
Gravar em um arquivo de texto.Write to a text file. Como gravar texto em um arquivoHow to: Write Text to a File
Ler de um arquivo de texto.Read from a text file. Como ler texto de um arquivoHow to: Read Text from a File
Acrescentar texto a um arquivo.Append text to a file. Como abrir e acrescentar a um arquivo de logHow to: Open and Append to a Log File

File.AppendText

FileInfo.AppendText
Obter o tamanho de um arquivo.Get the size of a file. FileInfo.Length
Obter os atributos de um arquivo.Get the attributes of a file. File.GetAttributes
Defina os atributos de um arquivo.Set the attributes of a file. File.SetAttributes
Determine se um arquivo existe.Determine if a file exists. File.Exists
Ler de um arquivo binário.Read from a binary file. Como ler e gravar em um arquivo de dados recém-criadoHow to: Read and Write to a Newly Created Data File
Gravar em um arquivo binário.Write to a binary file. Como ler e gravar em um arquivo de dados recém-criadoHow to: Read and Write to a Newly Created Data File

Confira também

Aplica-se a

Write(Byte[])

Grava uma matriz de bytes no fluxo subjacente.Writes a byte array to the underlying stream.

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())

Parâmetros

buffer
Byte[]

Uma matriz de bytes que contém os dados a serem gravados.A byte array containing the data to write.

Exceções

Ocorre um erro de E/S.An I/O error occurs.

O fluxo está fechado.The stream is closed.

buffer é null.buffer is null.

Exemplos

O exemplo de código a seguir mostra como gravar dados binários usando a memória como um repositório de backup e, em seguida, verificar se os dados foram gravados corretamente.The following code example shows how to write binary data using memory as a backing store, and then verify that the data was written correctly.

using namespace System;
using namespace System::IO;
int main()
{
   const int arrayLength = 1000;
   
   // Create random data to write to the stream.
   array<Byte>^dataArray = gcnew array<Byte>(arrayLength);
   (gcnew Random)->NextBytes( dataArray );
   BinaryWriter^ binWriter = gcnew BinaryWriter( gcnew 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 = gcnew BinaryReader( binWriter->BaseStream );
   
   // Set the stream position to the beginning of the stream.
   binReader->BaseStream->Position = 0;
   
   // Read and verify the data.
   array<Byte>^verifyArray = binReader->ReadBytes( arrayLength );
   if ( verifyArray->Length != arrayLength )
   {
      Console::WriteLine( "Error writing the data." );
      return  -1;
   }

   for ( int i = 0; i < arrayLength; i++ )
   {
      if ( verifyArray[ i ] != dataArray[ i ] )
      {
         Console::WriteLine( "Error writing the data." );
         return  -1;
      }

   }
   Console::WriteLine( "The data was written and verified." );
}

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.");
    }
}
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

Comentários

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Aplica-se a

Write(Byte)

Grava um byte sem sinal no fluxo atual e avança a posição do fluxo em um byte.Writes an unsigned byte to the current stream and advances the stream position by one 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)

Parâmetros

value
Byte

O byte sem sinal a gravar.The unsigned byte to write.

Exceções

Ocorre um erro de E/S.An I/O error occurs.

O fluxo está fechado.The stream is closed.

Exemplos

O exemplo de código a seguir mostra como gravar dados binários usando a memória como um repositório de backup e, em seguida, verificar se os dados foram gravados corretamente.The following code example shows how to write binary data using memory as a backing store, and then verify that the data was written correctly.

using namespace System;
using namespace System::IO;
int main()
{
   int i = 0;
   
   // Create random data to write to the stream.
   array<Byte>^writeArray = gcnew array<Byte>(1000);
   (gcnew Random)->NextBytes( writeArray );
   BinaryWriter^ binWriter = gcnew BinaryWriter( gcnew MemoryStream );
   BinaryReader^ binReader = gcnew 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  -1;
         }

      }
      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 );
   }

}

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);
        }
    }
}
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

Comentários

Devido a conflitos de formatação de dados, não é recomendável usar este método com as seguintes codificações:Because of data formatting conflicts, using this method with the following encodings is not recommended:

  • UTF-7UTF-7

  • ISO-2022-JPISO-2022-JP

  • ISCIIISCII

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Aplica-se a

Write(Boolean)

Grava um valor Boolean de um byte no fluxo atual, com 0 representando false e 1 representando true.Writes a one-byte Boolean value to the current stream, with 0 representing false and 1 representing 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)

Parâmetros

value
Boolean

O valor Boolean a ser gravado (0 ou 1).The Boolean value to write (0 or 1).

Exceções

Ocorre um erro de E/S.An I/O error occurs.

O fluxo está fechado.The stream is closed.

Exemplos

O exemplo de código a seguir demonstra como armazenar e recuperar configurações de aplicativo em um arquivo.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

Comentários

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Aplica-se a

Write(Int64)

Grava um inteiro com sinal de oito bytes no fluxo atual e avança a posição do fluxo em oito bytes.Writes an eight-byte signed integer to the current stream and advances the stream position by eight bytes.

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)

Parâmetros

value
Int64

O inteiro com sinal de oito bytes a ser gravado.The eight-byte signed integer to write.

Exceções

Ocorre um erro de E/S.An I/O error occurs.

O fluxo está fechado.The stream is closed.

Comentários

BinaryWriter armazena esse tipo de dados no formato little endian.BinaryWriter stores this data type in little endian format.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Aplica-se a