Hola a todos, hoy os voy a explicar como podemos escribir un fichero de texto en C#.
Para escribir en un fichero de texto con C#, lo podemos hacer con StreamWriter y su método WriteLine, pasandole una cadena como parámetro.
La forma de crear un StreamWriter es la siguiente:
|
1 |
System.IO.StreamWriter outputFile = new System.IO.StreamWriter("ejemplo.txt"); |
Si queremos que se añada al texto que ya hay en el fichero:
|
1 |
System.IO.StreamWriter outputFile = new System.IO.StreamWriter("ejemplo.txt", true); |
Ahora vamos a escribir lineas, en mi caso lo voy a guardar en un array de string:
|
1 2 3 4 5 6 |
string[] lineas = { "Linea 1", "Linea 2", "Linea 3" }; foreach (string linea in lineas) { outputFile.WriteLine(linea); } |
Recuerda siempre cerrar el fichero:
|
1 |
outputFile.Close(); |
También os recomiendo poner un try catch para evitar errores:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
try { System.IO.StreamWriter outputFile = new System.IO.StreamWriter("ejemplo.txt"); string[] lineas = { "Linea 1", "Linea 2", "Linea 3" }; foreach (string linea in lineas) { outputFile.WriteLine(linea); } Console.WriteLine("Fichero escrito"); outputFile.Close(); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } |
Este es el contenido del fichero:

Os dejo un vídeo donde lo explico paso a paso:
Os dejo el ejemplo completo:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EscribirFicheroTexto { class Program { static void Main(string[] args) { System.IO.StreamWriter outputFile = new System.IO.StreamWriter("ejemplo.txt"); string[] lineas = { "Linea 1", "Linea 2", "Linea 3" }; foreach (string linea in lineas) { outputFile.WriteLine(linea); } Console.WriteLine("Fichero escrito"); outputFile.Close(); Console.ReadLine(); } } } |
Espero que os sea de ayuda. Si tenéis dudas, preguntad. Estamos para ayudarte.
Deja una respuesta