SlideShare una empresa de Scribd logo
Módulo I- Introducción a la Programación en
la Plataforma .Net con C#
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
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()
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.
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;
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
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();
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();
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

Más contenido relacionado

La actualidad más candente

Informe estructuras no lineales
Informe estructuras no linealesInforme estructuras no lineales
Informe estructuras no lineales
eliezerbs
 
Archivos secuenciales-indexados C++
Archivos secuenciales-indexados C++Archivos secuenciales-indexados C++
Archivos secuenciales-indexados C++
EdsonRc
 
Bryan gordillo ensayo_ficheros
Bryan gordillo ensayo_ficherosBryan gordillo ensayo_ficheros
Bryan gordillo ensayo_ficheros
Bryan Gordillo
 
Cuestionario 2
Cuestionario 2Cuestionario 2
Cuestionario 2
juanitavpr
 

La actualidad más candente (20)

Archivos secuenciales indexados
Archivos secuenciales indexadosArchivos secuenciales indexados
Archivos secuenciales indexados
 
Manejo de archivos en el lenguaje C
Manejo de archivos en el lenguaje CManejo de archivos en el lenguaje C
Manejo de archivos en el lenguaje C
 
Jyoc java-cap14 persistencia. ficheros corrientes
Jyoc java-cap14 persistencia. ficheros corrientesJyoc java-cap14 persistencia. ficheros corrientes
Jyoc java-cap14 persistencia. ficheros corrientes
 
Informe tecnico u 4-victor uex
Informe tecnico u 4-victor uexInforme tecnico u 4-victor uex
Informe tecnico u 4-victor uex
 
Informe estructuras no lineales
Informe estructuras no linealesInforme estructuras no lineales
Informe estructuras no lineales
 
Definición de pila (1)
Definición de pila (1)Definición de pila (1)
Definición de pila (1)
 
Lenguajes de Marcas XML
Lenguajes de Marcas XMLLenguajes de Marcas XML
Lenguajes de Marcas XML
 
Bryan gordillo ensayo_ficheros
Bryan gordillo ensayo_ficherosBryan gordillo ensayo_ficheros
Bryan gordillo ensayo_ficheros
 
Archivos
ArchivosArchivos
Archivos
 
Medotos de busqueda gbi
Medotos de busqueda gbiMedotos de busqueda gbi
Medotos de busqueda gbi
 
11 archivos guia numero 4
11 archivos guia numero 411 archivos guia numero 4
11 archivos guia numero 4
 
Archivos secuenciales-indexados C++
Archivos secuenciales-indexados C++Archivos secuenciales-indexados C++
Archivos secuenciales-indexados C++
 
Grupo 1 Archivos Secuenciales Indexados en C++
Grupo 1 Archivos Secuenciales Indexados en C++Grupo 1 Archivos Secuenciales Indexados en C++
Grupo 1 Archivos Secuenciales Indexados en C++
 
Archivo secuencial indexado
Archivo secuencial indexadoArchivo secuencial indexado
Archivo secuencial indexado
 
Utilizacion de archivos en Dev C++
Utilizacion de archivos en Dev C++Utilizacion de archivos en Dev C++
Utilizacion de archivos en Dev C++
 
Archivos Secuenciales Indexados
Archivos Secuenciales IndexadosArchivos Secuenciales Indexados
Archivos Secuenciales Indexados
 
Bryan gordillo ensayo_ficheros
Bryan gordillo ensayo_ficherosBryan gordillo ensayo_ficheros
Bryan gordillo ensayo_ficheros
 
Cuestionario 2
Cuestionario 2Cuestionario 2
Cuestionario 2
 
ellenguajedec++
ellenguajedec++ellenguajedec++
ellenguajedec++
 
Access 2007
Access 2007Access 2007
Access 2007
 

Destacado

Mi lenguaje de programación de preferencia es C++
Mi lenguaje de programación de preferencia es C++Mi lenguaje de programación de preferencia es C++
Mi lenguaje de programación de preferencia es C++
N_Alejandrino
 
Estudio comparativo de PHP, ASP.NET Y JAVA
Estudio comparativo de PHP, ASP.NET Y JAVAEstudio comparativo de PHP, ASP.NET Y JAVA
Estudio comparativo de PHP, ASP.NET Y JAVA
Helmilpa
 
Lenguajes De Programación Web
Lenguajes De Programación WebLenguajes De Programación Web
Lenguajes De Programación Web
ragmyl
 
Tipos de datos C#
Tipos de datos C#Tipos de datos C#
Tipos de datos C#
alex28Xx
 
Reading Photographs
Reading PhotographsReading Photographs
Reading Photographs
Tjkoos
 
Подсистема Лаборатория, МИС Пациент
Подсистема Лаборатория, МИС ПациентПодсистема Лаборатория, МИС Пациент
Подсистема Лаборатория, МИС Пациент
Medotrade
 
Osiagniecia gim1 2013
Osiagniecia gim1  2013Osiagniecia gim1  2013
Osiagniecia gim1 2013
gim1mik
 

Destacado (20)

4 variables, arreglos, estructuras y enum
4 variables, arreglos, estructuras y enum4 variables, arreglos, estructuras y enum
4 variables, arreglos, estructuras y enum
 
Manejo de archivos en c#
Manejo de archivos en c#Manejo de archivos en c#
Manejo de archivos en c#
 
Mi lenguaje de programación de preferencia es C++
Mi lenguaje de programación de preferencia es C++Mi lenguaje de programación de preferencia es C++
Mi lenguaje de programación de preferencia es C++
 
Estudio comparativo de PHP, ASP.NET Y JAVA
Estudio comparativo de PHP, ASP.NET Y JAVAEstudio comparativo de PHP, ASP.NET Y JAVA
Estudio comparativo de PHP, ASP.NET Y JAVA
 
C sharp fundamentos
C sharp fundamentosC sharp fundamentos
C sharp fundamentos
 
Lenguajes De Programación Web
Lenguajes De Programación WebLenguajes De Programación Web
Lenguajes De Programación Web
 
Todo sobre C#
Todo sobre C#Todo sobre C#
Todo sobre C#
 
Tipos de datos C#
Tipos de datos C#Tipos de datos C#
Tipos de datos C#
 
Implementacion de bases de datos en mysql
Implementacion de bases de datos en mysqlImplementacion de bases de datos en mysql
Implementacion de bases de datos en mysql
 
Leadgeneratie via social media in kennisintensieve B2B-organisaties
Leadgeneratie via social media in kennisintensieve B2B-organisatiesLeadgeneratie via social media in kennisintensieve B2B-organisaties
Leadgeneratie via social media in kennisintensieve B2B-organisaties
 
Reading Photographs
Reading PhotographsReading Photographs
Reading Photographs
 
Bou categojuiprofesor
Bou categojuiprofesorBou categojuiprofesor
Bou categojuiprofesor
 
Tugas bhs inggris
Tugas bhs inggrisTugas bhs inggris
Tugas bhs inggris
 
Consecuencias primera guera mundial
Consecuencias primera guera mundialConsecuencias primera guera mundial
Consecuencias primera guera mundial
 
0 kg medicine ppt
0 kg medicine ppt0 kg medicine ppt
0 kg medicine ppt
 
Подсистема Лаборатория, МИС Пациент
Подсистема Лаборатория, МИС ПациентПодсистема Лаборатория, МИС Пациент
Подсистема Лаборатория, МИС Пациент
 
Formulas METODOS CURVAS IPR
Formulas METODOS CURVAS IPRFormulas METODOS CURVAS IPR
Formulas METODOS CURVAS IPR
 
Osiagniecia gim1 2013
Osiagniecia gim1  2013Osiagniecia gim1  2013
Osiagniecia gim1 2013
 
Tno & bcc sustainability forum10thsept2012
Tno & bcc sustainability forum10thsept2012Tno & bcc sustainability forum10thsept2012
Tno & bcc sustainability forum10thsept2012
 
120906a syd start pitch
120906a syd start pitch120906a syd start pitch
120906a syd start pitch
 

Similar a 7 manejo de archivos

PERSISTENCIA BASADA EN ARCHIVOS
PERSISTENCIA BASADA EN ARCHIVOSPERSISTENCIA BASADA EN ARCHIVOS
PERSISTENCIA BASADA EN ARCHIVOS
Darwin Durand
 
Fichero c y c++
Fichero c y c++Fichero c y c++
Fichero c y c++
mauro0210
 
Manejo+de+archivos+en+java
Manejo+de+archivos+en+javaManejo+de+archivos+en+java
Manejo+de+archivos+en+java
Whaleejaa Wha
 
Manejo de archivos en java
Manejo de archivos en javaManejo de archivos en java
Manejo de archivos en java
Whaleejaa Wha
 
Manejo de archivos en java
Manejo de archivos en javaManejo de archivos en java
Manejo de archivos en java
Whaleejaa Wha
 
Manejo de archivos en java
Manejo de archivos en javaManejo de archivos en java
Manejo de archivos en java
MaiirOn Gaitan
 
Navigating The File System
Navigating The File SystemNavigating The File System
Navigating The File System
kayrambal
 
Navegar Sistema De Archivos
Navegar Sistema De ArchivosNavegar Sistema De Archivos
Navegar Sistema De Archivos
kayrambal
 
Curso scjp 30 navegacion de archivos e io
Curso scjp 30   navegacion de archivos e ioCurso scjp 30   navegacion de archivos e io
Curso scjp 30 navegacion de archivos e io
programadorjavablog
 
Open And Reading Files
Open And Reading FilesOpen And Reading Files
Open And Reading Files
kayrambal
 
Framework .NET 3.5 14 Gestión de archivos y serialización
Framework .NET 3.5 14  Gestión de archivos y serializaciónFramework .NET 3.5 14  Gestión de archivos y serialización
Framework .NET 3.5 14 Gestión de archivos y serialización
Antonio Palomares Sender
 

Similar a 7 manejo de archivos (20)

Tema1oficial
Tema1oficialTema1oficial
Tema1oficial
 
Archivos
ArchivosArchivos
Archivos
 
PERSISTENCIA BASADA EN ARCHIVOS
PERSISTENCIA BASADA EN ARCHIVOSPERSISTENCIA BASADA EN ARCHIVOS
PERSISTENCIA BASADA EN ARCHIVOS
 
Fichero c y c++
Fichero c y c++Fichero c y c++
Fichero c y c++
 
Manejo+de+archivos+en+java
Manejo+de+archivos+en+javaManejo+de+archivos+en+java
Manejo+de+archivos+en+java
 
Manejo de archivos en java
Manejo de archivos en javaManejo de archivos en java
Manejo de archivos en java
 
Manejo de archivos en java
Manejo de archivos en javaManejo de archivos en java
Manejo de archivos en java
 
Manejo de archivos en java
Manejo de archivos en javaManejo de archivos en java
Manejo de archivos en java
 
Lab archivos
Lab archivosLab archivos
Lab archivos
 
Lab6-POO
Lab6-POOLab6-POO
Lab6-POO
 
Navigating The File System
Navigating The File SystemNavigating The File System
Navigating The File System
 
Navegar Sistema De Archivos
Navegar Sistema De ArchivosNavegar Sistema De Archivos
Navegar Sistema De Archivos
 
Archivos en c clase unsam
Archivos en c clase unsamArchivos en c clase unsam
Archivos en c clase unsam
 
Curso scjp 30 navegacion de archivos e io
Curso scjp 30   navegacion de archivos e ioCurso scjp 30   navegacion de archivos e io
Curso scjp 30 navegacion de archivos e io
 
Open And Reading Files
Open And Reading FilesOpen And Reading Files
Open And Reading Files
 
Acceso a datos
Acceso a datosAcceso a datos
Acceso a datos
 
Grupo nro4ficheros
Grupo nro4ficherosGrupo nro4ficheros
Grupo nro4ficheros
 
Archivos
ArchivosArchivos
Archivos
 
Framework .NET 3.5 14 Gestión de archivos y serialización
Framework .NET 3.5 14  Gestión de archivos y serializaciónFramework .NET 3.5 14  Gestión de archivos y serialización
Framework .NET 3.5 14 Gestión de archivos y serialización
 
Objetivo 01 Archivos de Texto
Objetivo 01 Archivos de TextoObjetivo 01 Archivos de Texto
Objetivo 01 Archivos de Texto
 

Más de Claribel Eusebio Nolasco (6)

9 fundamentos de oo
9 fundamentos de oo9 fundamentos de oo
9 fundamentos de oo
 
6 excepciones
6 excepciones6 excepciones
6 excepciones
 
5 metodos y parametros
5 metodos y parametros5 metodos y parametros
5 metodos y parametros
 
3 condicionales y ciclos
3 condicionales y ciclos3 condicionales y ciclos
3 condicionales y ciclos
 
1 introduccion microsoft .net
1 introduccion microsoft .net1 introduccion microsoft .net
1 introduccion microsoft .net
 
10 sintaxis oo
10 sintaxis oo10 sintaxis oo
10 sintaxis oo
 

Último

PRÁCTICAS DEL MÓDULO I Y II DE EDUCACIÓN Y SOCIEDAD.docx
PRÁCTICAS DEL MÓDULO I Y II DE EDUCACIÓN Y SOCIEDAD.docxPRÁCTICAS DEL MÓDULO I Y II DE EDUCACIÓN Y SOCIEDAD.docx
PRÁCTICAS DEL MÓDULO I Y II DE EDUCACIÓN Y SOCIEDAD.docx
encinasm992
 
(PROYECTO) Límites entre el Arte, los Medios de Comunicación y la Informática
(PROYECTO) Límites entre el Arte, los Medios de Comunicación y la Informática(PROYECTO) Límites entre el Arte, los Medios de Comunicación y la Informática
(PROYECTO) Límites entre el Arte, los Medios de Comunicación y la Informática
vazquezgarciajesusma
 
proyecto invernadero desde el departamento de tecnología para Erasmus
proyecto invernadero desde el departamento de tecnología para Erasmusproyecto invernadero desde el departamento de tecnología para Erasmus
proyecto invernadero desde el departamento de tecnología para Erasmus
raquelariza02
 

Último (20)

Posnarrativas en la era de la IA generativa
Posnarrativas en la era de la IA generativaPosnarrativas en la era de la IA generativa
Posnarrativas en la era de la IA generativa
 
Trabajo Coding For kids 1 y 2 grado 9-4.pdf
Trabajo Coding For kids 1 y 2 grado 9-4.pdfTrabajo Coding For kids 1 y 2 grado 9-4.pdf
Trabajo Coding For kids 1 y 2 grado 9-4.pdf
 
proyectos_social_y_socioproductivos _mapas_conceptuales
proyectos_social_y_socioproductivos _mapas_conceptualesproyectos_social_y_socioproductivos _mapas_conceptuales
proyectos_social_y_socioproductivos _mapas_conceptuales
 
Estudio de la geometría analitica. Pptx.
Estudio de la geometría analitica. Pptx.Estudio de la geometría analitica. Pptx.
Estudio de la geometría analitica. Pptx.
 
ACTIVIDAD DE TECNOLOGÍA AÑO LECTIVO 2024
ACTIVIDAD DE TECNOLOGÍA AÑO LECTIVO 2024ACTIVIDAD DE TECNOLOGÍA AÑO LECTIVO 2024
ACTIVIDAD DE TECNOLOGÍA AÑO LECTIVO 2024
 
HerramientasInformaticas ¿Que es? - ¿Para que sirve? - Recomendaciones - Comp...
HerramientasInformaticas ¿Que es? - ¿Para que sirve? - Recomendaciones - Comp...HerramientasInformaticas ¿Que es? - ¿Para que sirve? - Recomendaciones - Comp...
HerramientasInformaticas ¿Que es? - ¿Para que sirve? - Recomendaciones - Comp...
 
PRÁCTICAS DEL MÓDULO I Y II DE EDUCACIÓN Y SOCIEDAD.docx
PRÁCTICAS DEL MÓDULO I Y II DE EDUCACIÓN Y SOCIEDAD.docxPRÁCTICAS DEL MÓDULO I Y II DE EDUCACIÓN Y SOCIEDAD.docx
PRÁCTICAS DEL MÓDULO I Y II DE EDUCACIÓN Y SOCIEDAD.docx
 
¡Mira mi nuevo diseño hecho en Canva!.pdf
¡Mira mi nuevo diseño hecho en Canva!.pdf¡Mira mi nuevo diseño hecho en Canva!.pdf
¡Mira mi nuevo diseño hecho en Canva!.pdf
 
Trabajo Coding For kids 1 y 2 grado 9-4.pdf
Trabajo Coding For kids 1 y 2 grado 9-4.pdfTrabajo Coding For kids 1 y 2 grado 9-4.pdf
Trabajo Coding For kids 1 y 2 grado 9-4.pdf
 
Gestión de concurrencia y bloqueos en SQL Server
Gestión de concurrencia y bloqueos en SQL ServerGestión de concurrencia y bloqueos en SQL Server
Gestión de concurrencia y bloqueos en SQL Server
 
lenguaje algebraico.pptx álgebra, trigonometria
lenguaje algebraico.pptx álgebra, trigonometrialenguaje algebraico.pptx álgebra, trigonometria
lenguaje algebraico.pptx álgebra, trigonometria
 
Robótica educativa para la eduacion primaria .pptx
Robótica educativa para la eduacion primaria .pptxRobótica educativa para la eduacion primaria .pptx
Robótica educativa para la eduacion primaria .pptx
 
Diagrama de flujo - ingenieria de sistemas 5to semestre
Diagrama de flujo - ingenieria de sistemas 5to semestreDiagrama de flujo - ingenieria de sistemas 5to semestre
Diagrama de flujo - ingenieria de sistemas 5to semestre
 
herramientas informaticas mas utilizadas
herramientas informaticas mas utilizadasherramientas informaticas mas utilizadas
herramientas informaticas mas utilizadas
 
Licencias para el Uso y el Desarrollo de Software
Licencias para el Uso y el Desarrollo de SoftwareLicencias para el Uso y el Desarrollo de Software
Licencias para el Uso y el Desarrollo de Software
 
HIGADO Y TRAUMA HEPATICO UDABOL 2024 (3).pdf
HIGADO  Y TRAUMA HEPATICO UDABOL 2024 (3).pdfHIGADO  Y TRAUMA HEPATICO UDABOL 2024 (3).pdf
HIGADO Y TRAUMA HEPATICO UDABOL 2024 (3).pdf
 
(PROYECTO) Límites entre el Arte, los Medios de Comunicación y la Informática
(PROYECTO) Límites entre el Arte, los Medios de Comunicación y la Informática(PROYECTO) Límites entre el Arte, los Medios de Comunicación y la Informática
(PROYECTO) Límites entre el Arte, los Medios de Comunicación y la Informática
 
Unidad 1- Historia y Evolucion de las computadoras.pdf
Unidad 1- Historia y Evolucion de las computadoras.pdfUnidad 1- Historia y Evolucion de las computadoras.pdf
Unidad 1- Historia y Evolucion de las computadoras.pdf
 
proyecto invernadero desde el departamento de tecnología para Erasmus
proyecto invernadero desde el departamento de tecnología para Erasmusproyecto invernadero desde el departamento de tecnología para Erasmus
proyecto invernadero desde el departamento de tecnología para Erasmus
 
Introducción a la robótica con arduino..pptx
Introducción a la robótica con arduino..pptxIntroducción a la robótica con arduino..pptx
Introducción a la robótica con arduino..pptx
 

7 manejo de archivos

  • 1. Módulo I- Introducción a la Programación en la Plataforma .Net con C#
  • 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

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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