FileStream.WriteByte(Byte) FileStream.WriteByte(Byte) FileStream.WriteByte(Byte) FileStream.WriteByte(Byte) Method

Definición

Escribe un byte en la posición actual de la secuencia de archivo.Writes a byte to the current position in the file stream.

public:
 override void WriteByte(System::Byte value);
public override void WriteByte (byte value);
override this.WriteByte : byte -> unit
Public Overrides Sub WriteByte (value As Byte)

Parámetros

value
Byte Byte Byte Byte

Un byte que se va a escribir en la secuencia.A byte to write to the stream.

Excepciones

La secuencia no admite escritura.The stream does not support writing.

Ejemplos

En el ejemplo de código siguiente se muestra cómo escribir datos en un archivo, byte por byte y, a continuación, comprobar que los datos se escribieron correctamente.The following code example shows how to write data to a file, byte by byte, and then verify that the data was written correctly.

using namespace System;
using namespace System::IO;
int main()
{
   String^ fileName =  "Test@##@.dat";
   
   // Create random data to write to the file.
   array<Byte>^dataArray = gcnew array<Byte>(100000);
   (gcnew Random)->NextBytes( dataArray );
   FileStream^ fileStream = gcnew FileStream( fileName,FileMode::Create );
   try
   {
      
      // Write the data to the file, byte by byte.
      for ( int i = 0; i < dataArray->Length; i++ )
      {
         fileStream->WriteByte( dataArray[ i ] );

      }
      
      // Set the stream position to the beginning of the file.
      fileStream->Seek( 0, SeekOrigin::Begin );
      
      // Read and verify the data.
      for ( int i = 0; i < fileStream->Length; i++ )
      {
         if ( dataArray[ i ] != fileStream->ReadByte() )
         {
            Console::WriteLine( "Error writing data." );
            return  -1;
         }

      }
      Console::WriteLine( "The data was written to {0} "
      "and verified.", fileStream->Name );
   }
   finally
   {
      fileStream->Close();
   }

}

using System;
using System.IO;

class FStream
{
    static void Main()
    {
        const string fileName = "Test#@@#.dat";

        // Create random data to write to the file.
        byte[] dataArray = new byte[100000];
        new Random().NextBytes(dataArray);

        using(FileStream  
            fileStream = new FileStream(fileName, FileMode.Create))
        {
            // Write the data to the file, byte by byte.
            for(int i = 0; i < dataArray.Length; i++)
            {
                fileStream.WriteByte(dataArray[i]);
            }

            // Set the stream position to the beginning of the file.
            fileStream.Seek(0, SeekOrigin.Begin);

            // Read and verify the data.
            for(int i = 0; i < fileStream.Length; i++)
            {
                if(dataArray[i] != fileStream.ReadByte())
                {
                    Console.WriteLine("Error writing data.");
                    return;
                }
            }
            Console.WriteLine("The data was written to {0} " +
                "and verified.", fileStream.Name);
        }
    }
}
Imports Microsoft.VisualBasic
Imports System
Imports System.IO
Imports System.Text

Class FStream

    Shared Sub Main()

        Const fileName As String = "Test#@@#.dat"

        ' Create random data to write to the file.
        Dim dataArray(100000) As Byte
        Dim randomGenerator As New Random()
        randomGenerator.NextBytes(dataArray)

        Dim fileStream As FileStream = _
            new FileStream(fileName, FileMode.Create)
        Try

            ' Write the data to the file, byte by byte.
            For i As Integer = 0 To dataArray.Length - 1
                fileStream.WriteByte(dataArray(i))
            Next i

            ' Set the stream position to the beginning of the stream.
            fileStream.Seek(0, SeekOrigin.Begin)

            ' Read and verify the data.
            For i As Integer = 0 To _
                CType(fileStream.Length, Integer) - 1

                If dataArray(i) <> fileStream.ReadByte() Then
                    Console.WriteLine("Error writing data.")
                    Return
                End If
            Next i
            Console.WriteLine("The data was written to {0} " & _
                "and verified.", fileStream.Name)
        Finally
            fileStream.Close()
        End Try
    
    End Sub
End Class

Comentarios

Este método invalida WriteByte.This method overrides WriteByte.

Utilice WriteByte para escribir un byte en un FileStream de forma eficaz.Use WriteByte to write a byte to a FileStream efficiently. Si la secuencia está cerrada o no es modificable, se producirá una excepción.If the stream is closed or not writable, an exception will be thrown.

Nota

Utilice la CanWrite propiedad para determinar si la instancia actual admite escritura.Use the CanWrite property to determine whether the current instance supports writing. Para obtener información adicional, vea CanWrite.For additional information, see CanWrite.

Notas a los desarrolladores de herederos

La implementación predeterminada de Stream crea una nueva matriz de un solo byte y, Write(Byte[], Int32, Int32)a continuación, llama a.The default implementation on Stream creates a new single-byte array and then calls Write(Byte[], Int32, Int32). Aunque esto es correcto, no es eficaz.While this is formally correct, it is inefficient. Cualquier flujo con un búfer interno debe invalidar este método y proporcionar una versión mucho más eficaz que lea el búfer directamente, evitando la asignación de matriz adicional en cada llamada.Any stream with an internal buffer should override this method and provide a much more efficient version that reads the buffer directly, avoiding the extra array allocation on every call.

Para obtener una lista de operaciones comunes de archivos y directorios, vea tareas de e/s comunes.For a list of common file and directory operations, see Common I/O Tasks.

Se aplica a

Consulte también: