Read and Write Text Files with C-Sharp

Reading and writing text files with C# is easy, and I'm going to show you how.  First, we're going to read some text from a file into a string.

using System.IO; // Don't forget to add at top of source

string outputString;

// 1.Read text directly from file
using (StreamReader sr = new StreamReader(@"C:\myfile.txt")) {
    outputString = sr.ReadToEnd();
}

// 2.Read text from stream
using (Stream s = File.OpenRead(@"C:\myfile.txt")) {
    using (StreamReader sr = new StreamReader(s)) {
        outputString = sr.ReadToEnd();
    }
}

We start by declaring the string outputString.  The next lines are placed in using statements so that we don't have to worry about forgetting the sr.Close(), otherwise you will get an exception if the file is accessed since the stream isn't closed.  In the first example, we use the StreamReader class to open a file at the given path.  In the second example, we are opening a file and reading the data to a new stream, giving the StreamReader class the newly created stream.  Both examples put the string from sr.ReadToEnd() into outputString, which can be returned or dealt with however you choose.

Next we're going to write a string to a text file.  It's just as simple to write as it is to read.

using System.IO; // Don't forget to add at top of source


string myText = "Hello there!";

using (StreamWriter sw = new StreamWriter(@"C:\myfile.txt")){
    sw.Write(myText);
}

using (Stream s = File.Create(@"C:\myfile.txt")) {
    using (StreamWriter sw = new StreamWriter(s)) {
        sw.Write(myText);
    }
}

As you can see from the example, writing a text file is almost exactly the same as writing.  Instead of using the StreamReader class, we simply use the StreamWriter class.