Leer y escribir en un fichero binario

2056 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.



csharp
  1. using System.IO;
  2. using System;
  3.  
  4. void FicheroBinario(string NombreFichero)
  5. {
  6.     BinaryReader br = null;
  7.     BinaryWriter bw = null;
  8.     FileStream fs = null;
  9.     try
  10.     {
  11.         if (!File.Exists(NombreFichero))
  12.         {
  13.             // No existe, lo creamos
  14.             bw = new BinaryWriter(File.Create(NombreFichero));
  15.             for (int i=0; i<10; i++)
  16.                 bw.Write(i);
  17.             bw.Close();
  18.         }
  19.         // abrimos su contenido y lo mostramos en la cónsola
  20.         fs = File.Open(NombreFichero, FileMode.Open);
  21.         br = new BinaryReader(fs);
  22.         while (fs.Position < fs.Length)
  23.             Console.Write(br.ReadInt32());
  24.         Console.WriteLine("\nFin de fichero");
  25.     }
  26.     finally
  27.     {
  28.         if (br!=null) br.Close();
  29.         if (bw!=null) bw.Close();
  30.     }
  31. }