logo

¿Cómo leer y escribir un archivo de texto en C#?

La finalización de un programa conlleva la eliminación de todos los datos relacionados con él. Por lo tanto, necesitamos almacenar los datos en algún lugar. Los archivos se utilizan para almacenar y compartir datos de forma permanente. C# se puede utilizar para recuperar y manipular datos almacenados en archivos de texto.

Leyendo un archivo de texto: La clase de archivo en C# define dos métodos estáticos para leer un archivo de texto, a saber Archivo.ReadAllText() y Archivo.ReadAllLines() .



  • File.ReadAllText() lee el archivo completo a la vez y devuelve una cadena. Necesitamos almacenar esta cadena en una variable y usarla para mostrar el contenido en la pantalla.
  • File.ReadAllLines() lee un archivo una línea a la vez y devuelve esa línea en formato de cadena. Necesitamos una serie de cadenas para almacenar cada línea. Mostramos el contenido del archivo usando la misma matriz de cadenas.

Hay otra forma de leer un archivo y es mediante el uso de un objeto StreamReader. StreamReader también lee una línea a la vez y devuelve una cadena. Todas las formas mencionadas anteriormente de leer un archivo se ilustran en el código de ejemplo que se proporciona a continuación.








// C# program to illustrate how> // to read a file in C#> using> System;> using> System.IO;> > class> Program {> >static> void> Main(>string>[] args)> >{> >// Store the path of the textfile in your system> >string> file =>@'M:DocumentsTextfile.txt'>;> > >Console.WriteLine(>'Reading File using File.ReadAllText()'>);> > >// To read the entire file at once> >if> (File.Exists(file)) {> >// Read all the content in one string> >// and display the string> >string> str = File.ReadAllText(file);> >Console.WriteLine(str);> >}> >Console.WriteLine();> > >Console.WriteLine(>'Reading File using File.ReadAllLines()'>);> > >// To read a text file line by line> >if> (File.Exists(file)) {> >// Store each line in array of strings> >string>[] lines = File.ReadAllLines(file);> > >foreach>(>string> ln>in> lines)> >Console.WriteLine(ln);> >}> >Console.WriteLine();> > >Console.WriteLine(>'Reading File using StreamReader'>);> > >// By using StreamReader> >if> (File.Exists(file)) {> >// Reads file line by line> >StreamReader Textfile =>new> StreamReader(file);> >string> line;> > >while> ((line = Textfile.ReadLine()) !=>null>) {> >Console.WriteLine(line);> >}> > >Textfile.Close();> > >Console.ReadKey();> >}> >Console.WriteLine();> >}> }>

>

>

diferencia entre amor y gusto

Para ejecutar este programa, guarde el archivo con .cs extensión y luego se puede ejecutar usando csc nombre de archivo.cs comando en cmd. O puede utilizar Visual Studio. Aquí tenemos un archivo de texto llamado Archivo de texto.txt que tienen el contenido que se muestra en la salida.

Producción:

leyendo archivo de texto en C#

Escribir un archivo de texto: La clase Archivo en C# define dos métodos estáticos para escribir un archivo de texto, a saber Archivo.WriteAllText() y Archivo.WriteAllLines() .

  • File.WriteAllText() escribe el archivo completo a la vez. Se necesitan dos argumentos, la ruta del archivo y el texto que se debe escribir.
  • File.WriteAllLines() escribe un archivo una línea a la vez. Se necesitan dos argumentos, la ruta del archivo y el texto que se debe escribir, que es una matriz de cadenas.

Hay otra forma de escribir en un archivo y es mediante el uso de un objeto StreamWriter. StreamWriter también escribe una línea a la vez. Los tres métodos de escritura crean un archivo nuevo si el archivo no existe, pero si el archivo ya está presente en esa ubicación especificada, se sobrescribe. Todas las formas mencionadas anteriormente de escribir en un archivo de texto se ilustran en el código de ejemplo que se proporciona a continuación.




// C# program to illustrate how> // to write a file in C#> using> System;> using> System.IO;> > class> Program {> >static> void> Main(>string>[] args)> >{> >// Store the path of the textfile in your system> >string> file =>@'M:DocumentsTextfile.txt'>;> > >// To write all of the text to the file> >string> text =>'This is some text.'>;> >File.WriteAllText(file, text);> > >// To display current contents of the file> >Console.WriteLine(File.ReadAllText(file));> >Console.WriteLine();> > >// To write text to file line by line> >string>[] textLines1 = {>'This is the first line'>,> >'This is the second line'>,> >'This is the third line'> };> > >File.WriteAllLines(file, textLines1);> > >// To display current contents of the file> >Console.WriteLine(File.ReadAllText(file));> > >// To write to a file using StreamWriter> >// Writes line by line> >string>[] textLines2 = {>'This is the new first line'>,> >'This is the new second line'> };> > >using>(StreamWriter writer =>new> StreamWriter(file))> >{> >foreach>(>string> ln>in> textLines2)> >{> >writer.WriteLine(ln);> >}> >}> >// To display current contents of the file> >Console.WriteLine(File.ReadAllText(file));> > >Console.ReadKey();> >}> }>

>

>

Para ejecutar este programa, guarde el archivo con .cs extensión y luego se puede ejecutar usando csc nombre de archivo.cs comando en cmd. O puede utilizar Visual Studio.

Producción:

escribir un archivo en C#

impresión javascript

En caso de que desee agregar más texto a un archivo existente sin sobrescribir los datos ya almacenados en él, puede utilizar los métodos de adición proporcionados por la clase Archivo de System.IO.




using> System;> using> System.IO;> > class> Program {> >static> void> Main(>string>[] args)> >{> >// Store the path of the textfile in your system> >string> file =>@'M:DocumentsTextfile.txt'>;> > >// To write all of the text to the file> >string> text1 =>'This is some text.'>;> >File.WriteAllText(file, text1);> > >// To append text to a file> >string> text2 =>'This is text to be appended'>;> >File.AppendAllText(file, text2);> > >// To display current contents of the file> >Console.WriteLine(File.ReadAllText(file));> >Console.ReadKey();> >}> }>

>

>

Producción:

agregar texto en un archivo en C#