Read all the contents of a text file

Asked

Viewed 604 times

11

I need to read all the contents of a text file and put it into a string.

Usually, I do so:

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 any other way or method that does this in a simpler way?

  • 2

    One day, when I go to study C#, I’ll remember that question :)

2 answers

16


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

The code above would look like this:

var texto = File.ReadAllText("arquivo.txt");
  • 1

    All right, but mine is more complete :P

10

Browser other questions tagged

You are not signed in. Login or sign up in order to post.