C# Text File

Thumbnail image of Jason Bauer
Jason Bauer
December 23, 2015 (Last Updated: ) | Reading Time: 1 minutes

C# makes it extraordinarily easy to read and write text files. There is a static object called "File" (located in System.IO) that does all the hard work for you.

Simple Example of Reading a File in C#

Look at how easy it is to read in a file, do some simple string processing on it, and then write it back out.

// open a text file and read all contents into a var
var text = File.ReadAllText(@"c:\temp\input.txt");

// use RegEx to search for dog and replace it with cat ignoring case
text = Regex.Replace(text, "dog", "cat", RegexOptions.IgnoreCase);

// write the result out to a file
File.WriteAllText(@"c:\temp\output.txt", Text);

C# Read Text File

To read the contents of a text file into a variable, all you need is a single line.

var text = File.ReadAllText(@"c:\temp\input.txt");

By the way, the @ symbol in the file path tells the compiler to treat the backslashes as actual backslashes. If you do not use the @ symbol then you need to use double backslashes like this "\\" instead.

C# Write Text File

To write a variable to a text file is equally easy.

File.WriteAllText(@"c:\temp\output.txt", "This text will be in the file");

When this line runs the file will be opened for write, the entire string will be written, and then the file will be closed. If the file already existed it will be overwritten. If you want to instead append to the end of the file simply change "Write" to "Append".

File.AppendAllText(@"c:\temp\output.txt", "This text will be in the file");

This will open the file for append, add the text on to the end, and then close the file. If you want a newline you need to specify it yourself.

C# TextStream

If you prefer to use streams there is a very simple way to open a text file in C# as a stream.

// get a stream handle to a file
var ts = File.OpenText(@"c:\temp\input.txt");

// now you can handle it like any other stream
while (!ts.EndOfStream)
{
    var line = ts.ReadLine();
}

There are many ways to handle file I/O in C# so that you can choose the one that is right for you. Any of the methods above are a fine way to read and write text files in C#.

Leave a reply

Thank you! Your comment has been successfully submitted. It will be approved as soon as possible.

More from Efundies