Este documento introduce el manejo de archivos en C# utilizando las clases File, FileInfo, Directory, DirectoryInfo, Stream, BinaryReader y BinaryWriter. Explica cómo leer y escribir datos de archivos de texto y binarios, y también cómo manipular directorios. Propone dos ejercicios para practicar el uso de estas clases al guardar y leer datos de usuarios de un archivo.
2. TEMARIO
CAPITULO III.- INTRODUCCIÓN AL
LENGUAJE DE PROGRAMACIÓN C#
Introducción Manejo Archivos
Utilizando las Clases File y
FileInfo
Utilizando la Clase Stream
3. INTRODUCCIÓN MANEJO DE ARCHIVOS
Manejo de Archivos
Interactuar con archivos es un común requerimiento de muchas aplicaciones.
El Namespace System.IO contiene un conjunto de clases que simplifican la interacción
con el sistema de archivo, ejemplo: Las clases File and FileInfo.
La Clase Files: La Clase FileInfo:
Copy() CopyTo()
Create() Delete()
Delete() Length
Exists() Open()
4. Escribiendo y Leyendo de Archivos Utilizando File y
FileInfo
Leyendo data desde archivo
string filePath = "myFile.txt";
...
byte[] data = File.ReadAllBytes(filePath); // Datos
Binarios.
string[] lines = File.ReadAllLines(filePath); //
Lectura Por Lineas.
string data = File.ReadAllText(filePath); // Archivo
completo.
Escribiendo data en archivo
string filePath = "myFile.txt";
...
string[] fileLines = {"Line 1", "Line 2", "Line 3"};
File.AppendAllLines(filePath, fileLines); //
Concatenar Lineas.
File.WriteAllLines(filePath, fileLines); // Escribir
por linea.
...
string fileContents = "I am writing this text to a
file ...“; File.AppendAllText(filePath, fileContents);
// Concatenar texto..
File.WriteAllText(filePath, fileContents); // Escribir
todas las lineas.
5. Manipulando Directorios
El Namespace System.IO contiene las clases Directory y DirectoryInfo las cuales ayudan a
simplificar la interacción con directorios
Clase Directory
string dirPath = @"C:UsersStudentMyDirectory";
...
Directory.CreateDirectory(dirPath);
Directory.Delete(dirPath);
string[] dirs = Directory.GetDirectories(dirPath);
string[] files = Directory.GetFiles(dirPath);
Clase DirectoryInfo
string dirPath = @"C:UsersStudentMyDirectory";
DirectoryInfo dir = new DirectoryInfo(dirPath);
...
bool exists = dir.Exists;
DirectoryInfo[] dirs = dir.GetDirectories();
FileInfo[] files = dir.GetFiles();
string fullName = dir.FullName;
6. Que es un Streams?
Un Stream es un mecanismo que nos permite manipular los datos en
partes manejables.
0100011
1110010
1010010
Fuente Aplicación Repositori
o
7. Leyendo y Escribiendo Datos Binarios
FileStream sourceFile = new
FileStream(sourceFilePath);
BinaryReader reader = new BinaryReader(sourceFile);
int position = 0;
int length = (int)reader.BaseStream.Length;
byte[] dataCollection = new byte[length];
int returnedByte;
while ((returnedByte = reader.Read()) != -1)
{
dataCollection[position] = (byte)returnedByte;
position += sizeof(byte);
} Clase BinaryReader
reader.Close();
sourceFile.Close();
byte[] dataCollection = { 1, 4, 6, 7, 12, 33, 26, 98,
82, 101 };
FileStream destFile = new
FileStream(destinationFilePath);
BinaryWriter writer = new BinaryWriter(destFile);
foreach (byte data in dataCollection)
{
writer.Write(data);
}
writer.Close(); Clase BinaryWriter
destFile.Close();
8. Leyendo y Escribiendo Texto
FileStream sourceFile = new
FileStream(sourceFilePath);
StreamReader reader = new StreamReader(sourceFile);
StringBuilder fileContents = new StringBuilder();
while (reader.Peek() != -1)
{
fileContents.Append((char)reader.Read());
}
string data = fileContents.ToString();
reader.Close(); Clase StreamReader
sourceFile.Close();
FileStream destFile = new FileStream(“...");
StreamWriter writer = new StreamWriter(destFile);
writer.WriteLine(“Hola, Esto se escribira en el
archivo");
writer.Close();
Clase StreamWriter
destFile.Close();
9. Ejercicios
1. Desarrollar un programa que guarde y lea de un
archivo utilizando la clase (File o FileInfo) los
siguientes dato: Cedula, Nombre, Apellido,
Teléfono, Fecha Nacimiento. El programa debe
permitir escribir un máximo de 5 registros con los
datos especificados. El menú consiste de una
opción para escribir y otra de lectura que mostrara
cada registro con sus datos en pantalla.
2. Desarrollar el programa anterior utilizando
FileStream, StreamWriter y StreamReader
Notas del editor
Explain that a common requirement for many applications is the ability to interact with files that are stored on the Windows file system. Explain that, to simplify these interactions and save you from writing the low-level code to interact directly with the Windows application programming interface (API), the .NET Framework provides several classes in the System.IO namespace. Describe the common methods of the File class shown on the slide, but point students to the complete list, with examples, in the Course Handbook. Highlight that the methods of the File class are static. Similarly, describe the common methods of the FileInfo class that enable an application to interact with files. Point out to students that the Course Handbook contains a complete list with code examples. Highlight that the methods of the FileInfo class are instance methods. Question: In your application, you use files as a temporary storage mechanism while the application is running. When the application stops running, you want to make sure that the file exists, and then delete the file. What is the easiest way to achieve this? Answer: The easiest approach would be to use the static Exists and Delete methods of the File class. Additional Reading For more information about the File class, see the File Class page at http://go.microsoft.com/fwlink/?LinkId=192915. For more information about the FileInfo class, see the FileInfo Class page at http://go.microsoft.com/fwlink/?LinkId=192916. Module 5: Reading and Writing Files Course 10266 A
Explain that you can read and write data from files by using the File and FileInfo classes, but that this lesson concentrates on the methods that are available through the File class. (Streams and the methods that are exposed through the FileInfo class are covered in Lesson 2.) Explain that you can read and write data in a variety of ways: as binary data, line by line, and by reading or writing the entire contents of a file and storing it in a string. Explain that you can either append to an existing file or create a new file and write the data to that file. Mention that the code examples on the slide show a subset of the methods that are available. The Course Handbook contains a fuller list, with code examples. You can use the FileSystemApplication solution in the E:\\Demofiles\\Mod5\\Samplecode\\ folder to demonstrate this topic. Question: In your application, you have just added some logic to handle exceptions. You now want to extend this logic further to store details of these exceptions to a log file on the file system so that you can diagnose any problems. You will be writing a string variable and you should want to never overwrite any existing log records in a file. Which method would you use? Answer: The AppendAllText method. Module 5: Reading and Writing Files Course 10266 A
Explain that the System.IO namespace includes the Directory and DirectoryInfo classes that help simplify the interactions with directories and folders on the file system. Mention that the Directory class contains only static methods and serves as a utility class for various directory-related functions. Explain that the DirectoryInfo class provides several instance methods and properties that enable you to wrap a directory on the file system and then interact with it. Use the code examples on the slide to illustrate some of the functions that are available with the Directory and DirectoryInfo classes. Point out that the Course Handbook contains additional examples. Note : Students may not have encountered the @ symbol at this point, so briefly explain that you can use it to create verbatim strings that include escape characters. You can use the FileSystemApplication solution in the E:\\Demofiles\\Mod5\\Samplecode\\ folder to demonstrate this topic. Question: What class would you use to retrieve an instance of a directory in the file system, which you can then interact with? Answer: You would create an instance of the DirectoryInfo class by using the default constructor passing in the path to the directory. Additional Reading For more information about the Directory class, see the Directory Class page at http://go.microsoft.com/fwlink/?LinkId=192917. For more information about the DirectoryInfo class, see the DirectoryInfo Class page at http://go.microsoft.com/fwlink/?LinkId=192918. Module 5: Reading and Writing Files Course 10266 A
This is an animated slide. Before you click any buttons, explain that, when working with data (in a file system, network, and so on), the data sometimes becomes too large to load into memory and transmit in a single atomic operation. Explain that streams enable you to read and write data in smaller chunks: [Click 1] Explain that a large file can be broken into smaller chunks. [Click 2] Explain that each chunk can then be transmitted without consuming all available resources (memory, network bandwidth, and so on). Explain that, in the .NET Framework, streams typically provide three operations: the ability to read, the ability to write, and the ability to seek. Mention that the .NET Framework provides several stream classes to enable you to work with a variety of data sources. Some of these are going to be explained in the next topics. Question: What do you think are the benefits of streaming data? Answer: Answers should include: The ability to read and write large amounts of data without consuming resources such as memory and network bandwidth. Not needing to load the entire amount of data into memory. Enabling your application to handle any amount of data, regardless of size. Additional Reading For more information about the FileStream class, see the FileStream Class page at http://go.microsoft.com/fwlink/?LinkId=192920. Module 5: Reading and Writing Files Course 10266 A
Highlight that many applications store data in raw binary form because writing binary is fast, it takes up less space on disk, and it is not human-readable. Explain that the .NET Framework class library contains classes that you can use to read and write data in a stream that you have opened by using a FileStream object. The code examples on the slide use the binary stream classes to read and write raw binary. Describe how the BinaryReader and BinaryWriter classes read and write binary data, using the code examples on the slide. Explain that, when using the BinaryReader or BinaryWriter classes, you must provide the stream that will access the data source. Explain that we are using the FileStream class. Mention that, to write binary data, you just need to call the Write method and pass in the value that you want to write. T o read binary data, you can use any of the Read<Type> methods that are provided. Explain that you can use the BinaryReader and BinaryWriter classes to read and write any primitive data type ( bool , int , double , byte , string , and so on). Explain that it is important to close the streams after use to release file handles and flush any data to the underlying streams. You can use the FileSystemApplication solution in the E:\\Demofiles\\Mod5\\Samplecode\\ folder to demonstrate this topic. Question: Why is it important to close streams when you have finished using them? Answer: To release any file handles, and flush data to the underlying streams. Module 5: Reading and Writing Files Course 10266 A
Explain that writing plain text to a file is very useful, whether you have a core business requirement to satisfy, or you want to add some custom trace logic to your application for debugging in the live environment. Mention that the .NET Framework provides the StreamReader and StreamWriter classes to enable you to read and write plain text. Explain that the StreamReader and StreamWriter classes follow the same streaming mode as the BinaryReader and BinaryWriter classes, in that they enable you to write data to an underlying stream that has a handle on the data source. You can use the FileSystemApplication solution in the E:\\Demofiles\\Mod5\\Samplecode\\ folder to demonstrate this topic. Question: You want to write a series of strings to a text file, and add a line break after each string. What is the easiest way to achieve this? Answer: Write the string by using the WriteLine method of the StreamWriter class. Additional Reading For more information about the StreamWriter class, see the StreamWriter Class page at http://go.microsoft.com/fwlink/?LinkId=192921. For more information about the StreamReader class, see the StreamReader Class page at http://go.microsoft.com/fwlink/?LinkId=192922. Module 5: Reading and Writing Files Course 10266 A