BinaryWriter.Write Método

Definición

Escribe un valor en la secuencia actual.Writes a value to the current stream.

Sobrecargas

Write(Char[], Int32, Int32)

Escribe una sección de una matriz de caracteres en la secuencia actual y avanza la posición actual de la secuencia de acuerdo con el Encoding utilizado y quizás los caracteres específicos que se escriben en la secuencia.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)

Escribe una región de una matriz de bytes en la secuencia actual.Writes a region of a byte array to the current stream.

Write(UInt64)

Escribe un entero sin signo de ocho bytes en la secuencia actual y avanza la posición de la secuencia en ocho bytes.Writes an eight-byte unsigned integer to the current stream and advances the stream position by eight bytes.

Write(UInt32)

Escribe un entero sin signo de cuatro bytes en la secuencia actual y avanza la posición de la secuencia en cuatro bytes.Writes a four-byte unsigned integer to the current stream and advances the stream position by four bytes.

Write(UInt16)

Escribe un entero sin signo de dos bytes en la secuencia actual y avanza la posición de la secuencia en dos bytes.Writes a two-byte unsigned integer to the current stream and advances the stream position by two bytes.

Write(String)

Escribe una cadena de longitud prefijada en esta secuencia en la codificación actual de BinaryWriter y hace avanzar la posición actual de la secuencia de acuerdo con la codificación utilizada y los caracteres específicos escritos en dicha secuencia.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)

Escribe un valor de punto flotante de cuatro bytes en la secuencia actual y avanza la posición de la secuencia en cuatro bytes.Writes a four-byte floating-point value to the current stream and advances the stream position by four bytes.

Write(SByte)

Escribe un byte con signo en la secuencia actual y avanza la posición de la secuencia en un byte.Writes a signed byte to the current stream and advances the stream position by one byte.

Write(ReadOnlySpan<Char>)

Escribe un intervalo de caracteres en la secuencia actual y avanza la posición actual de la secuencia de acuerdo con el elemento Encoding utilizado y quizás los caracteres específicos que se escriben en la secuencia.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>)

Escribe un intervalo de bytes en la secuencia actual.Writes a span of bytes to the current stream.

Write(Char)

Escribe un carácter Unicode en la secuencia actual y avanza la posición actual de la secuencia de acuerdo con el Encoding utilizado y los caracteres específicos escritos en la secuencia.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)

Escribe un entero con signo de cuatro bytes en la secuencia actual y avanza la posición de la secuencia en cuatro bytes.Writes a four-byte signed integer to the current stream and advances the stream position by four bytes.

Write(Int16)

Escribe un entero con signo de dos bytes en la secuencia actual y avanza la posición de la secuencia en dos bytes.Writes a two-byte signed integer to the current stream and advances the stream position by two bytes.

Write(Double)

Escribe un valor de punto flotante de ocho bytes en la secuencia actual y avanza la posición de la secuencia en ocho bytes.Writes an eight-byte floating-point value to the current stream and advances the stream position by eight bytes.

Write(Decimal)

Escribe un valor decimal en la secuencia actual y avanza la posición de la secuencia en dieciséis bytes.Writes a decimal value to the current stream and advances the stream position by sixteen bytes.

Write(Char[])

Escribe una matriz de caracteres en la secuencia actual y avanza la posición actual de la secuencia de acuerdo con el Encoding utilizado y los caracteres específicos escritos en esa secuencia.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[])

Escribe una matriz de bytes en la secuencia subyacente.Writes a byte array to the underlying stream.

Write(Byte)

Escribe un byte sin signo en la secuencia actual y avanza la posición de la secuencia en un byte.Writes an unsigned byte to the current stream and advances the stream position by one byte.

Write(Boolean)

Escribe un valor Boolean de un byte en la secuencia actual, que es 0 si es false y 1 si es true.Writes a one-byte Boolean value to the current stream, with 0 representing false and 1 representing true.

Write(Int64)

Escribe un entero con signo de ocho bytes en la secuencia actual y avanza la posición de la secuencia en ocho bytes.Writes an eight-byte signed integer to the current stream and advances the stream position by eight bytes.

Write(Char[], Int32, Int32)

Escribe una sección de una matriz de caracteres en la secuencia actual y avanza la posición actual de la secuencia de acuerdo con el Encoding utilizado y quizás los caracteres específicos que se escriben en la secuencia.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[]

Matriz de caracteres que contiene los datos que se van a escribir.A character array containing the data to write.

index
Int32

Índice del primer carácter que se lee de chars y se escribe en la secuencia.The index of the first character to read from chars and to write to the stream.

count
Int32

Número de caracteres que se leen de chars y se escriben en la secuencia.The number of characters to read from chars and to write to the stream.

Excepciones

La longitud del búfer menos index es menor que count.The buffer length minus index is less than count.

chars es null.chars is null.

index o count es negativo.index or count is negative.

Error de E/S.An I/O error occurs.

La secuencia está cerrada.The stream is closed.

Ejemplos

En el ejemplo de código siguiente se muestra cómo leer y escribir datos mediante la memoria como una memoria auxiliar.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

Comentarios

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Consulte también

Se aplica a

Write(Byte[], Int32, Int32)

Escribe una región de una matriz de bytes en la secuencia actual.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[]

Matriz de bytes que contiene los datos que se van a escribir.A byte array containing the data to write.

index
Int32

Índice del primer byte que se lee de buffer y se escribe en la secuencia.The index of the first byte to read from buffer and to write to the stream.

count
Int32

Número de bytes que se leen de buffer y se escriben en la secuencia.The number of bytes to read from buffer and to write to the stream.

Excepciones

La longitud del búfer menos index es menor que count.The buffer length minus index is less than count.

buffer es null.buffer is null.

index o count es negativo.index or count is negative.

Error de E/S.An I/O error occurs.

La secuencia está cerrada.The stream is closed.

Ejemplos

En el ejemplo de código siguiente se muestra cómo escribir datos binarios mediante la memoria como una memoria auxiliar y, a continuación, comprobar que los datos se escribieron correctamente.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

Comentarios

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Se aplica a

Write(UInt64)

Importante

Esta API no es conforme a CLS.

Escribe un entero sin signo de ocho bytes en la secuencia actual y avanza la posición de la secuencia en ocho 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

Entero sin signo de ocho bytes que se va a escribir.The eight-byte unsigned integer to write.

Atributos

Excepciones

Error de E/S.An I/O error occurs.

La secuencia está cerrada.The stream is closed.

Comentarios

BinaryWriter almacena este tipo de datos en formato de little endian.BinaryWriter stores this data type in little endian format.

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Se aplica a

Write(UInt32)

Importante

Esta API no es conforme a CLS.

Escribe un entero sin signo de cuatro bytes en la secuencia actual y avanza la posición de la secuencia en cuatro 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

Entero sin signo de cuatro bytes que se va a escribir.The four-byte unsigned integer to write.

Atributos

Excepciones

Error de E/S.An I/O error occurs.

La secuencia está cerrada.The stream is closed.

Comentarios

BinaryWriter almacena este tipo de datos en formato de little endian.BinaryWriter stores this data type in little endian format.

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Se aplica a

Write(UInt16)

Importante

Esta API no es conforme a CLS.

Escribe un entero sin signo de dos bytes en la secuencia actual y avanza la posición de la secuencia en dos 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

Entero sin signo de dos bytes que se va a escribir.The two-byte unsigned integer to write.

Atributos

Excepciones

Error de E/S.An I/O error occurs.

La secuencia está cerrada.The stream is closed.

Comentarios

BinaryWriter almacena este tipo de datos en formato de little endian.BinaryWriter stores this data type in little endian format.

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Se aplica a

Write(String)

Escribe una cadena de longitud prefijada en esta secuencia en la codificación actual de BinaryWriter y hace avanzar la posición actual de la secuencia de acuerdo con la codificación utilizada y los caracteres específicos escritos en dicha secuencia.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

Valor que se va a escribir.The value to write.

Excepciones

Error de E/S.An I/O error occurs.

value es null.value is null.

La secuencia está cerrada.The stream is closed.

Ejemplos

En el ejemplo de código siguiente se muestra cómo almacenar y recuperar la configuración de la aplicación en un archivo.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

Comentarios

El prefijo de longitud significa que este método escribe primero la longitud de la cadena, en bytes, cuando se codifica con la BinaryWriter codificación actual de la instancia en la secuencia.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. Este valor se escribe como un entero sin signo.This value is written as an unsigned integer. A continuación, este método escribe ese número de bytes en la secuencia.This method then writes that many bytes to the stream.

Por ejemplo, la cadena "A" tiene una longitud de 1, pero cuando se codifica con UTF-16; la longitud es 2 bytes, por lo que el valor escrito en el prefijo es 2 y se escriben 3 bytes en la secuencia, incluido el prefijo.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 obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Consulte también

Se aplica a

Write(Single)

Escribe un valor de punto flotante de cuatro bytes en la secuencia actual y avanza la posición de la secuencia en cuatro 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

Valor de punto flotante de cuatro bytes que se va a escribir.The four-byte floating-point value to write.

Excepciones

Error de E/S.An I/O error occurs.

La secuencia está cerrada.The stream is closed.

Ejemplos

En el ejemplo de código siguiente se muestra cómo almacenar y recuperar la configuración de la aplicación en un archivo.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

Comentarios

BinaryWriter almacena este tipo de datos en formato de little endian.BinaryWriter stores this data type in little endian format.

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Se aplica a

Write(SByte)

Importante

Esta API no es conforme a CLS.

Escribe un byte con signo en la secuencia actual y avanza la posición de la secuencia en un 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

Byte con signo que se va a escribir.The signed byte to write.

Atributos

Excepciones

Error de E/S.An I/O error occurs.

La secuencia está cerrada.The stream is closed.

Comentarios

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Se aplica a

Write(ReadOnlySpan<Char>)

Escribe un intervalo de caracteres en la secuencia actual y avanza la posición actual de la secuencia de acuerdo con el elemento Encoding utilizado y quizás los caracteres específicos que se escriben en la secuencia.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>

Intervalo de caracteres que se va a escribir.A span of chars to write.

Se aplica a

Write(ReadOnlySpan<Byte>)

Escribe un intervalo de bytes en la secuencia actual.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>

Intervalo de bytes que se va a escribir.The span of bytes to write.

Se aplica a

Write(Char)

Escribe un carácter Unicode en la secuencia actual y avanza la posición actual de la secuencia de acuerdo con el Encoding utilizado y los caracteres específicos escritos en la secuencia.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

El carácter Unicode no suplente que se va a escribir.The non-surrogate, Unicode character to write.

Excepciones

Error de E/S.An I/O error occurs.

La secuencia está cerrada.The stream is closed.

ch es un carácter suplente único.ch is a single surrogate character.

Ejemplos

En el ejemplo de código siguiente se muestra cómo leer y escribir datos mediante la memoria como una memoria auxiliar.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

Comentarios

Debido a conflictos de formato de datos, no se recomienda usar este método con las codificaciones siguientes: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 obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Los caracteres suplentes Unicode se deben escribir como pares en la misma llamada, no individualmente.Unicode surrogate characters must be written out as pairs together in the same call, not individually. Si necesita compatibilidad con pares suplentes en la aplicación, considere la posibilidad de usar una matriz de caracteres y la Write sobrecarga del método.If you require support for surrogate pairs in your application, consider using a character array and the Write method overload.

Consulte también

Se aplica a

Write(Int32)

Escribe un entero con signo de cuatro bytes en la secuencia actual y avanza la posición de la secuencia en cuatro 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

Entero con signo de cuatro bytes que se va a escribir.The four-byte signed integer to write.

Excepciones

Error de E/S.An I/O error occurs.

La secuencia está cerrada.The stream is closed.

Ejemplos

En el ejemplo de código siguiente se muestra cómo almacenar y recuperar la configuración de la aplicación en un archivo.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

Comentarios

BinaryWriter almacena este tipo de datos en formato de little endian.BinaryWriter stores this data type in little endian format.

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Se aplica a

Write(Int16)

Escribe un entero con signo de dos bytes en la secuencia actual y avanza la posición de la secuencia en dos 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

Entero con signo de dos bytes que se va a escribir.The two-byte signed integer to write.

Excepciones

Error de E/S.An I/O error occurs.

La secuencia está cerrada.The stream is closed.

Comentarios

BinaryWriter almacena este tipo de datos en formato de little endian.BinaryWriter stores this data type in little endian format.

En la tabla siguiente se muestran ejemplos de otras tareas de e/s típicas o relacionadas.The following table lists examples of other typical or related I/O tasks.

Para...To do this... Vea el ejemplo de este tema...See the example in this topic...
Crear un archivo de textoCreate a text file. Cómo: Escribir texto en un archivoHow to: Write Text to a File
Escribir en un archivo de texto.Write to a text file. Cómo: Escribir texto en un archivoHow to: Write Text to a File
Leer de un archivo de texto.Read from a text file. Cómo: Leer texto de un archivoHow to: Read Text from a File
Anexe texto a un archivo.Append text to a file. Cómo: Abrir y anexar a un archivo de registroHow to: Open and Append to a Log File

File.AppendText

FileInfo.AppendText
Obtiene el tamaño de un archivo.Get the size of a file. FileInfo.Length
Obtiene los atributos de un archivo.Get the attributes of a file. File.GetAttributes
Establecer los atributos de un archivo.Set the attributes of a file. File.SetAttributes
Determinar si existe un archivo.Determine if a file exists. File.Exists
Leer de un archivo binario.Read from a binary file. Cómo: Leer y escribir en un archivo de datos recién creadoHow to: Read and Write to a Newly Created Data File
Escribir en un archivo binario.Write to a binary file. Cómo: Leer y escribir en un archivo de datos recién creadoHow to: Read and Write to a Newly Created Data File

Se aplica a

Write(Double)

Escribe un valor de punto flotante de ocho bytes en la secuencia actual y avanza la posición de la secuencia en ocho 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

Valor de punto flotante de ocho bytes que se va a escribir.The eight-byte floating-point value to write.

Excepciones

Error de E/S.An I/O error occurs.

La secuencia está cerrada.The stream is closed.

Ejemplos

En el ejemplo de código siguiente se muestra cómo leer y escribir Double datos en la memoria mediante las BinaryReader BinaryWriter clases y en la parte superior de la MemoryStream clase.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 solo Lee y escribe Byte datos.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

Comentarios

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Se aplica a

Write(Decimal)

Escribe un valor decimal en la secuencia actual y avanza la posición de la secuencia en dieciséis 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

Valor decimal que se va a escribir.The decimal value to write.

Excepciones

Error de E/S.An I/O error occurs.

La secuencia está cerrada.The stream is closed.

Comentarios

En la tabla siguiente se muestran ejemplos de otras tareas de e/s típicas o relacionadas.The following table lists examples of other typical or related I/O tasks.

Para...To do this... Vea el ejemplo de este tema...See the example in this topic...
Crear un archivo de textoCreate a text file. Cómo: Escribir texto en un archivoHow to: Write Text to a File
Escribir en un archivo de texto.Write to a text file. Cómo: Escribir texto en un archivoHow to: Write Text to a File
Leer de un archivo de texto.Read from a text file. Cómo: Leer texto de un archivoHow to: Read Text from a File
Anexe texto a un archivo.Append text to a file. Cómo: Abrir y anexar a un archivo de registroHow to: Open and Append to a Log File

File.AppendText

FileInfo.AppendText
Obtiene el tamaño de un archivo.Get the size of a file. FileInfo.Length
Obtiene los atributos de un archivo.Get the attributes of a file. File.GetAttributes
Establecer los atributos de un archivo.Set the attributes of a file. File.SetAttributes
Determinar si existe un archivo.Determine if a file exists. File.Exists
Leer de un archivo binario.Read from a binary file. Cómo: Leer y escribir en un archivo de datos recién creadoHow to: Read and Write to a Newly Created Data File
Escribir en un archivo binario.Write to a binary file. Cómo: Leer y escribir en un archivo de datos recién creadoHow to: Read and Write to a Newly Created Data File

Se aplica a

Write(Char[])

Escribe una matriz de caracteres en la secuencia actual y avanza la posición actual de la secuencia de acuerdo con el Encoding utilizado y los caracteres específicos escritos en esa secuencia.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[]

Matriz de caracteres que contiene los datos que se van a escribir.A character array containing the data to write.

Excepciones

chars es null.chars is null.

La secuencia está cerrada.The stream is closed.

Error de E/S.An I/O error occurs.

Ejemplos

En el ejemplo de código siguiente se muestra cómo leer y escribir datos mediante la memoria como una memoria auxiliar.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

Comentarios

En la tabla siguiente se muestran ejemplos de otras tareas de e/s típicas o relacionadas.The following table lists examples of other typical or related I/O tasks.

Para...To do this... Vea el ejemplo de este tema...See the example in this topic...
Crear un archivo de textoCreate a text file. Cómo: Escribir texto en un archivoHow to: Write Text to a File
Escribir en un archivo de texto.Write to a text file. Cómo: Escribir texto en un archivoHow to: Write Text to a File
Leer de un archivo de texto.Read from a text file. Cómo: Leer texto de un archivoHow to: Read Text from a File
Anexe texto a un archivo.Append text to a file. Cómo: Abrir y anexar a un archivo de registroHow to: Open and Append to a Log File

File.AppendText

FileInfo.AppendText
Obtiene el tamaño de un archivo.Get the size of a file. FileInfo.Length
Obtiene los atributos de un archivo.Get the attributes of a file. File.GetAttributes
Establecer los atributos de un archivo.Set the attributes of a file. File.SetAttributes
Determinar si existe un archivo.Determine if a file exists. File.Exists
Leer de un archivo binario.Read from a binary file. Cómo: Leer y escribir en un archivo de datos recién creadoHow to: Read and Write to a Newly Created Data File
Escribir en un archivo binario.Write to a binary file. Cómo: Leer y escribir en un archivo de datos recién creadoHow to: Read and Write to a Newly Created Data File

Consulte también

Se aplica a

Write(Byte[])

Escribe una matriz de bytes en la secuencia subyacente.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[]

Matriz de bytes que contiene los datos que se van a escribir.A byte array containing the data to write.

Excepciones

Error de E/S.An I/O error occurs.

La secuencia está cerrada.The stream is closed.

buffer es null.buffer is null.

Ejemplos

En el ejemplo de código siguiente se muestra cómo escribir datos binarios mediante la memoria como una memoria auxiliar y, a continuación, comprobar que los datos se escribieron correctamente.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

Comentarios

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Se aplica a

Write(Byte)

Escribe un byte sin signo en la secuencia actual y avanza la posición de la secuencia en un 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

Byte sin signo que se va a escribir.The unsigned byte to write.

Excepciones

Error de E/S.An I/O error occurs.

La secuencia está cerrada.The stream is closed.

Ejemplos

En el ejemplo de código siguiente se muestra cómo escribir datos binarios mediante la memoria como una memoria auxiliar y, a continuación, comprobar que los datos se escribieron correctamente.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

Comentarios

Debido a conflictos de formato de datos, no se recomienda usar este método con las codificaciones siguientes: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 obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Se aplica a

Write(Boolean)

Escribe un valor Boolean de un byte en la secuencia actual, que es 0 si es false y 1 si es 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

Valor Boolean que se va a escribir (0 ó 1).The Boolean value to write (0 or 1).

Excepciones

Error de E/S.An I/O error occurs.

La secuencia está cerrada.The stream is closed.

Ejemplos

En el ejemplo de código siguiente se muestra cómo almacenar y recuperar la configuración de la aplicación en un archivo.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

Comentarios

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Se aplica a

Write(Int64)

Escribe un entero con signo de ocho bytes en la secuencia actual y avanza la posición de la secuencia en ocho 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

Entero con signo de ocho bytes que se va a escribir.The eight-byte signed integer to write.

Excepciones

Error de E/S.An I/O error occurs.

La secuencia está cerrada.The stream is closed.

Comentarios

BinaryWriter almacena este tipo de datos en formato de little endian.BinaryWriter stores this data type in little endian format.

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Se aplica a