C# Text File

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. Look at how easy it is to read in a file, do some simple string processing on it, and then write it back out.

C# Read Text File

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

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.

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”.

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.

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

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.