What's the best way to read the contents of a text file to a string in .NET?
-
09-06-2019 - |
Question
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;
}
}
Solution
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.
OTHER TIPS
string text = File.ReadAllText("c:\file1.txt");
File.WriteAllText("c:\file2.txt", text);
Also check out ReadAllLines/WriteAllLines and ReadAllBytes/WriteAllBytes
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();
}
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.