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

There seems to 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; } } 
+4
source share
4 answers

First of all, the header requires β€œhow to write the contents of strnig to a text file”, but your sample code is for β€œhow to read the contents of a text file in a line.

The 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 you need a string array or a byte array instead of a string.

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

Also check ReadAllLines / WriteAllLines and ReadAllBytes / WriteAllBytes

+5
source

There is no point in this exception handler. He does not do anything. This is just the standard version of your code, this is normal:

  private string LoadFromFile(string path) { using(StreamReader rdr = File.OpenText(path)) return rdr.ReadToEnd(); } 
+4
source

Can a .ReadAllText () file be?

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

+3
source

Source: https://habr.com/ru/post/1276534/


All Articles