Sei sulla pagina 1di 23

ICIN 082

Programación Avanzada
Semestre 2006/02- Prof.: Oscar Mapocho Salazar Cerna - mapocho@gmail.com

Clase 1
Archivos en C#
Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt
¿Qué es un archivo?

• Conjunto de información que se almacena en un


computador
• Se puede identificar por una “ruta”
• Equivalente informático a los archivos en tarjetas,
papel o microfichas
• Para el sistema operativo:
– Es simplemente un flujo unidimensional de bytes que
es tratado como una única unidad lógica
– Normalmente tiene un tamaño
– Depende del software que lo utiliza
Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt
Tipos de Archivo

• Archivos de texto
– Se pueden ver/modificar fácilmente
– Se requiere un editor de texto: Notepad
• Archivos binarios
– Dependen del software que los creó
– Si se pudieran ver … no se entiende nada
– Guardan estructuras complejas

Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt


¿Archivos en C#?

• Para guardar información en forma permanente


– A diferencia de memoria RAM
– Se puede guardar en disco duro, pendrive, disquete
• Para comunicarme con otro software
– Leer planilla
– Generar datos para ser leídos por Excel
– Generar datos para algoritmo de programación lineal

Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt


Uso de stream’s

• Stream es un canal de comunicación


• Alguien debe abrirlo por ambos lados
• Se puede leer desde él
• Se puede escribir en él

Stream

Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt


Antes deben conocer

• Usaremos:
– System.Text
– System.IO
• Clases:
– FileStream
– StreamReader
– StreamWriter
• Constantes:
– FileMode
– FileAccess

Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt


Ejemplo en C#
Lectura de archivo de texto
using System;
using System.Text;
using System.IO;

namespace ejemplo1
{
class MainClass
{
public static void Main(string[] args)
{
string fileName = "c:\\tmp\\icin082\\lista_correos.txt";
string linea;
FileStream stream = new FileStream(fileName, FileMode.Open,
FileAccess.Read);
StreamReader reader = new StreamReader(stream);

while (reader.Peek() > -1) {


linea= reader.ReadLine();
Console.WriteLine(linea);
}
reader.Close();
Console.ReadLine();
}
}
}

Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt


Ejemplo en C#
Escribiendo archivo de texto
using System;
using System.IO;

namespace ejemplo2
{
class MainClass
{
public static void Main(string[] args)
{
string fileName = "c:\\tmp\\icin082\\correlativo.txt";
FileStream stream = new FileStream(fileName,
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(stream);

for (int i=0; i<100; i++) {


writer.WriteLine("Linea #{0}",i);
}
writer.Close();
Console.ReadLine();
}
}
}
Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt
Ejemplo en C#
Creando y escribiendo archivo texto

using System;
using System.IO;

namespace ejemplo3
{
class MainClass
{
public static void Main(string[] args)
{
string fileName = "c:\\tmp\\icin082\\archivo_creado.txt";
StreamWriter writer = File.CreateText(fileName);

writer.WriteLine("Este es mi Nuevo archivo creado.");


writer.Close();
Console.ReadLine();
}
}
}

Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt


Ejemplo en C#
Agregando a archivo de texto
using System;
using System.IO;

namespace ejemplo4
{
class MainClass
{
public static void Main(string[] args)
{
try
{
string fileName = "c:\\tmp\\icin082\\agregando_a_archivo.txt";
// esto inserta texto en un archivo existente, si el archivo no existe lo crea
StreamWriter writer = File.AppendText(fileName);
writer.WriteLine("Este es el texto agregado.");
writer.Close();
Console.ReadLine();
}
catch
{
Console.WriteLine("Ocurrió un error.");
}
}
}
}

Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt


Ejemplo en C#
Leyendo archivo binario
using System;
using System.IO;

namespace ejemplo5
{
class MainClass
{
static void Main(string[] args)
{
try
{
string fileName = "c:\\tmp\\icin082\\lista_correos.txt";
int letter = 0;
FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(stream);

while (letter != -1)


{
letter = reader.Read();
if (letter != -1) Console.Write((char)letter);
}
reader.Close();
stream.Close();
Console.ReadLine();
}
catch
{
Console.WriteLine("Hubo un error");
}
}
}
}

Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt


Ejemplo en C#
Escribiendo archivo binario
using System;
using System.IO;

namespace ejemplo6
{
class MainClass
{
static void Main(string[] args)
{
try
{
string fileName = "c:\\tmp\\icin082\\archivo_binario.txt";
// data a ser guardada
int[] data = {0, 1, 2, 3, 4, 5};
FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter writer = new BinaryWriter(stream);

for(int i=0; i<data.Length; i++)


{
// números son guardados en formáto UTF-8 format (4 bytes)
writer.Write(data[i]);
}
writer.Close();
stream.Close();
Console.WriteLine("Ya fue creado el archivo.");
Console.ReadLine();
}
catch
{
Console.WriteLine("Hubo un error.");
}
}
}
}

Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt


ICIN 082
Programación Avanzada
Semestre 2006/02- Prof.: Oscar Mapocho Salazar Cerna - mapocho@gmail.com

Clase 2
Archivos en C#
Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt
Ejemplo en C#
Notas

• Desarrollar un programa en C# que


genere un archivo,
“notas_computacion.txt”, con las notas al
azar, entre 1 y 7, de las 5 pruebas del
curso de computación, para cada alumno
registrado en el archivo “lista_curso.txt”
• El formato del archivo debe quedar como
sigue:
– nombre_alumno, nota_prueba1, nota_prueba1, nota_prueba2

Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt


Ejemplo en C#
Promedio

• Desarrollar un programa en C# que lea un


archivo con notas,
“notas_computacion.txt”, y genere otro
igual, “notas_promediadas.txt”, pero
agregándole el promedio al final

Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt


ICIN 082
Programación Avanzada
Semestre 2006/02- Prof.: Oscar Mapocho Salazar Cerna - mapocho@gmail.com

Clase 3
Archivos en C#
Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt
Ejemplo #1
Textos
• Desarrollar un programa en C# que lea un
archivo de texto, “textos.txt”, el cual trae le
siguiente estructura (por línea):
– texto, x, y
– Para c/texto definido, dibujarlo en la pantalla.
• Utilizar:
– Un proyecto Windows Form
– using System.Windows.Forms;
– using System.Drawing;
– Ver artículo en:
• http://www.developer.com/net/csharp/article.php/1435391

Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt


Ejemplo #2
Círculos

• Desarrollar un programa en C# que lea un


archivo de texto, “circulos.txt”, el cual trae le
siguiente estructura (por línea):
– x, y, radio
• Para c/círculo definido, pintarlo en la pantalla.
• Utilizar:
– Lo mismo que ejemplo de textos más método:
• DrawEllipse(System.Drawing.Pen, float x, float y, float width, float height)

Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt


ICIN 082
Programación Avanzada
Semestre 2006/02- Prof.: Oscar Mapocho Salazar Cerna - mapocho@gmail.com

Clase 4
Estructuras de Datos: Listas
Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt
Ejemplo #1
Figuras

• Desarrollar un programa en C# que lea un


archivo de texto, “figuras.txt”, el cual trae la
siguiente estructura (por línea):
– tipo de figura, color, x1, y1, x2, y2
– Donde “tipo de figura” se refiere a:
• Punto
• Linea
• Circulo
• Rectangulo
Y pinte las figuras definidas

Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt


Estructuras de Datos

• Es una construcción que permite almacenar datos


de una manera compleja
• Se deben proveer los métodos para manipular la
información:
– Agregar
– Modificar
– Buscar
– Eliminar
• Sirve mucho implementar un pequeño programa
para pruebas

Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt


Ejemplo #2
Círculos

• Desarrollar un programa en C# que:


– Defina una clase mi_lista que permita
almacenar palabras (string) y una frecuencia
de aparición. Se deben incluir los siguientes
métodos:
• Agregar
• Buscar
• Sacar
• Eliminar
– Utilizar un arreglo

Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt


Ejemplo #3
Círculos

• Desarrollar un programa en C# que:


– Defina una clase linea compuesta por 2 puntos
• Constructor
• Pintor
– Utilizando la clase del ejercicio #2, implemente un
programa que lea una lista con líneas definidas en un
archivo, “lineas.txt” y luego las pinte
– El archivo tiene el siguiente formato:
• x1, y1, x2, y2, color

Depto. Ingeniería Industrial - Universidad Austral de Chile - Campus Puerto Montt

Potrebbero piacerti anche