Read the entire contents of a text file

11

I need to read the entire contents of a text file and put it in a string .

Generally, I do this:

using(var reader = new StreamReader("arquivo.txt"))
{
    var strBuilder = new StringBuilder();

    while (objReader.ReadLine() != null)
    {
        strBuilder.Append(objReader.ReadLine());
    }
}

var texto = strBuilder.ToString();

Is there another way or method that does this in a simpler way?

    
asked by anonymous 15.10.2015 / 19:22

2 answers

15

In the .NET Framework 2.0 and later, the File class has the ReadAllText() " that does just that.

The code above would look like this:

var texto = File.ReadAllText("arquivo.txt");
    
15.10.2015 / 19:22
10

Yes, since version 2.0 of the .Net Framework there is ReadAllText() .

var texto = File.ReadAllText("arquivo.txt");
    
15.10.2015 / 19:25