La forma más sencilla de leer y escribir archivos

Resuelto ApprenticeHacker asked hace 12 años • 14 respuestas

Hay muchas formas diferentes de leer y escribir archivos ( archivos de texto , no binarios) en C#.

Solo necesito algo que sea fácil y use la menor cantidad de código, porque voy a trabajar mucho con archivos en mi proyecto. Solo necesito algo stringporque todo lo que necesito es leer y escribir strings.

ApprenticeHacker avatar Sep 27 '11 20:09 ApprenticeHacker
Aceptado

Utilice File.ReadAllText y File.WriteAllText .

Extracto de ejemplo de MSDN:

// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);

...

// Open the file to read from.
string readText = File.ReadAllText(path);

Esta página enumera los diversos métodos auxiliares para tareas de E/S comunes.

vc 74 avatar Sep 27 '2011 13:09 vc 74

Además de File.ReadAllText, File.ReadAllLinesy File.WriteAllText(y ayudantes similares de Filela clase) que se muestran en otra respuesta , puedes usar StreamWriter/ StreamReaderclasses.

Escribir un archivo de texto:

using(StreamWriter writetext = new StreamWriter("write.txt"))
{
    writetext.WriteLine("writing in text file");
}

Leyendo un archivo de texto:

using(StreamReader readtext = new StreamReader("readme.txt"))
{
   string readText = readtext.ReadLine();
}

Notas:

  • Puede utilizar readtext.Dispose()en lugar de using, pero no cerrará el archivo/lector/escritor en caso de excepciones.
  • Tenga en cuenta que la ruta relativa es relativa al directorio de trabajo actual. Es posible que desee utilizar/construir una ruta absoluta.
  • Falta using/ Closees una razón muy común de "por qué los datos no se escriben en el archivo".
Bali C avatar Sep 27 '2011 13:09 Bali C
FileStream fs = new FileStream(txtSourcePath.Text,FileMode.Open, FileAccess.Read);
using(StreamReader sr = new StreamReader(fs))
{
   using (StreamWriter sw = new StreamWriter(Destination))
   {
            sw.Writeline("Your text");
    }
}
Swapnil avatar Feb 12 '2015 09:02 Swapnil

La forma más sencilla de leer un archivo y escribir en un archivo:

//Read from a file
string something = File.ReadAllText("C:\\Rfile.txt");

//Write to a file
using (StreamWriter writer = new StreamWriter("Wfile.txt"))
{
    writer.WriteLine(something);
}
yazarloo avatar May 30 '2016 09:05 yazarloo