using System;
using System.IO;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public class CEscribirBytes
{
public static void Main(string[] args)
{
FileStream fs = null;
byte[] buffer = new byte[81];
int nbytes = 0, car;
try
{
//Crear un flujo hacia el fichero texto.txt
fs = new FileStream("C:\\Datos\\texto.txt", FileMode.Create, FileAccess.Write);
Console.WriteLine("Escriba el texto que desea almacenar en el fichero:");
while ((car = Console.Read()) != '\r' && nbytes < buffer.Length)
{
buffer[nbytes] = (byte)car;
nbytes++;
}
//Escribir la linea de texto en el fichero
fs.Write(buffer, 0, nbytes);
}
catch (IOException e)
{
Console.WriteLine("Error: " + e.Message);
}
Console.ReadLine();
}
}
}
}
EJEMPLO 2
using System;
using System.IO;
using System.Text;
namespace ConsoleApplication1
{
public class CLeerBytes
{
public static void Main(string[] args)
{
FileStream fe = null;
char[] cBuffer = new char[81];
byte[] bBuffer = new byte[81];
int nbytes;
try
{
// Crear un flujo desde el fichero texto.text
fe = new FileStream("C:\\Datos\\texto.txt", FileMode.Open, FileAccess.Read);
//Leer del fichero un linea de texto
nbytes = fe.Read(bBuffer, 0, 81);
//Crear un objeto string con el texto leido
Array.Copy(bBuffer, cBuffer, bBuffer.Length);
String str = new String(cBuffer, 0, nbytes);
// Mostrar el texto leido
Console.WriteLine(str);
}
catch (IOException e)
{
Console.WriteLine("Error: " + e.Message);
}
finally
{
//Cerrar el fichero
if (fe != null) fe.Close();
}
Console.ReadLine();
}
}
}
EJEMPLO 3
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
public class CEscribirCars
{
static void Main(string[] args)
{
StreamWriter sw = null;
string str;
try
{
//Crar un flujo hacia el fichero doc.txt
sw = new StreamWriter("C:\\Datos\\doc.txt");
Console.WriteLine("Escriba las lineas de texto a almacenar en el fichero.\n" + "Finalice cada linea pulsando la tecla
//Leer la linea de la entrada estandar
str = Console.ReadLine();
while (str.Length != 0)
{
//Escribir la linea leida en el fichero
sw.WriteLine(str);
//Leer la linea siguiente
str = Console.ReadLine();
}
}
catch (IOException e)
{
Console.WriteLine("Error:" + e.Message);
}
finally
{
if (sw != null) sw.Close();
}
}
}
}
EJEMPLO 4
using System;
using System.IO;
public class CLeerCars
{
public static void Main(string[] args)
{
StreamReader sr = null;
String str;
try{
//Crear un flujo desde el fichero doc.txt
sr = new StreamReader("C:\\Datos\\doc.txt");
// Leer del fichero una linea de texto
str = sr.ReadLine();
while (str != null)
{
// Mostrar la linea leida
Console.WriteLine(str);
// Leer la linea siguiente
str = sr.ReadLine();
}
}
catch(IOException e)
{
Console.WriteLine("Error: " + e.Message);
}
finally
{
// cerrar el fichero
if (sr != null) sr.Close();
}
Console.ReadLine();
}
}