HOW TO: Read and Write To A File In C#

Hello everyone,

Occasionally I like to review the basics to make sure I am still on track and update myself if anything has changed. Today I will be reviewing how to read and write to a file in C#. There are two methods, the easy way and the standard way. The standard way looks a little something like this.

Reading contents from a file:

Writing contents to a file:

FileStream flsFileStream = File.Open("data.tmp", FileMode.Open, FileAccess.ReadWrite);
StreamWriter srwWriter = new StreamWriter(flsFileStream);
srwWriter.WriteLine("New line to text file.");

If you are looking for less code, this is the easy way to read from a file:

string text = File.ReadAllText(@"C:words.txt");

And this is an easy way to write to a file:

File.WriteAllText(@"C:words.txt", "File contents");

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>