Easiest way to read from and write to files

ApprenticeHacker picture ApprenticeHacker · Sep 27, 2011 · Viewed 578.5k times · Source

There are a lot of different ways to read and write files (text files, not binary) in C#.

I just need something that is easy and uses the least amount of code, because I am going to be working with files a lot in my project. I only need something for string since all I need is to read and write strings.

Answer

vc 74 picture vc 74 · Sep 27, 2011

Use File.ReadAllText and File.WriteAllText.

MSDN example excerpt:

// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);

...

// Open the file to read from.
string readText = File.ReadAllText(path);