views:

662

answers:

4

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;
   }
}
+3  A: 

File.ReadAllText() maybe?

ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/fxref_mscorlib/html/4803f846-3d8a-de8a-18eb-32cfcd038f76.htm if you have VS2008's help installed.

Brad Wilson
+4  A: 
string text = File.ReadAllText("c:\file1.txt");
File.WriteAllText("c:\file2.txt", text);

Also check out ReadAllLines/WriteAllLines and ReadAllBytes/WriteAllBytes

Chris Marasti-Georg
+15  A: 

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.

Jimmy
Be careful with ReadAllText or ReadAllLines on big files, especially if this code is running on the GUI thread.
RoadWarrior
+2  A: 

There's no point in that exception handler. It does nothing. This is just a shorterned version of your code, it's fine:

 private string LoadFromFile(string path)
 {
    using(StreamReader rdr = File.OpenText(path))
      return rdr.ReadToEnd();
 }
Bjorn Reppen