Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to read the contents of a text file to a string in .NET?

It seems like there should be something shorter than this:

private string LoadFromFile(string path)
{
   try
   {
       string fileContents;
       using(StreamReader rdr = File.OpenText(path))
       {
            fileContents = rdr.ReadToEnd();
       }

       return fileContents;
   }
   catch
   {
       throw;
   }
}
like image 672
Scott Lawrence Avatar asked Nov 28 '22 13:11

Scott Lawrence


2 Answers

First of all, the title asks for "how to write the contents of strnig to a text file" but your code example is for "how to read the contents of a text file to a string.

Answer to both questions:

using System.IO;
...
string filename = "C:/example.txt";
string content = File.ReadAllText(filename);
File.WriteAllText(filename, content);

See also ReadAllLines/WriteAllLines and ReadAllBytes/WriteAllBytes if instead of a string you want a string array or byte array.

like image 51
Jimmy Avatar answered Dec 19 '22 10:12

Jimmy


string text = File.ReadAllText("c:\file1.txt");
File.WriteAllText("c:\file2.txt", text);

Also check out ReadAllLines/WriteAllLines and ReadAllBytes/WriteAllBytes

like image 22
Chris Marasti-Georg Avatar answered Dec 19 '22 11:12

Chris Marasti-Georg