Leer y escribir en un fichero binario

1977 vistas

Vamos a crear un fichero binario y rellenarlo de enteros.
Mostraremos su contenido en pantalla.
Usaremos para ello la clase System.IO.BinaryReader para la lectura y System.IO.BinaryWriter para la escritura.



vbnet
  1.     Imports System.IO
  2.     Sub FichierBinaire(ByVal NombreFichero As String)
  3.         Dim br As BinaryReader
  4.         Dim bw As BinaryWriter
  5.         Dim fs As FileStream
  6.         Dim i As Integer
  7.         Try
  8.             If Not File.Exists(NombreFichero) Then
  9.                 ' No existe, lo creamos
  10.                 bw = New BinaryWriter(File.Create(NombreFichero))
  11.                 For i = 0 To 9
  12.                     bw.Write(i)
  13.                 Next
  14.                 bw.Close()
  15.             End If
  16.             ' abrimos su contenido y lo mostramos en la cónsola
  17.             fs = File.Open(NombreFichero, FileMode.Open)
  18.             br = New BinaryReader(fs)
  19.             Console.WriteLine("Debut du fichier")
  20.             While fs.Position < fs.Length
  21.                 Console.Write(br.ReadInt32())
  22.             End While
  23.             Console.WriteLine("{0}Fin de fichero", ControlChars.CrLf)
  24.         Finally
  25.             ' cerramos Binaryreader
  26.             If Not IsNothing(br) Then br.Close()
  27.             ' cerramos Binarywriter
  28.             If Not IsNothing(bw) Then bw.Close()
  29.         End Try
  30.     End Sub