Files

Reading/Writing files

File.WriteAllText creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.

File.AppendAllText appends the specified string to the file, creating the file if it does not already exist.

File.ReadAllText opens a text file, reads all the text in the file into a string, and then closes the file.

using System;
using System.IO;
using System.Text;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        // This text is added only once to the file.
        if (!File.Exists(path))
        {
            // Create a file to write to.
            string createText = "Hello and Welcome" + Environment.NewLine;
            File.WriteAllText(path, createText);
        }

        // This text is always added, making the file longer over time
        // if it is not deleted.
        string appendText = "This is extra text" + Environment.NewLine;
        File.AppendAllText(path, appendText);

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

These functions also exist as byte and line as well as async verions:

Funciton Byte Line Text
Write WriteAllBytes
WriteAllBytesAsync
WriteAllLines
WriteAllLinesAsync
WriteAllText
WriteAllTextAsync
Append - none - AppendAllLines
AppendAllLinesAsync
AppendAllText
AppendAllTextAsync
Read ReadAllBytes
ReadAllBytesAsync
ReadAllLines
ReadAllLinesAsync
ReadAllText
ReadAllTextAsync