All notes


File System and the Registry

File and Stream I/O

File IO

Read and write:

StreamWriter: Implements a TextWriter for writing characters to a stream in a particular encoding.

TextReader: Represents a reader that can read a sequential series of characters.

StringReader: Implements a TextReader that reads from a string.

static async void ReadCharacters()
    StringBuilder stringToRead = new StringBuilder();
    stringToRead.AppendLine("Characters in 1st line to read");
    stringToRead.AppendLine("and 2nd line");
    stringToRead.AppendLine("and the end");

    using (StringReader reader = new StringReader(stringToRead.ToString()))
        string readText = await reader.ReadToEndAsync();

Common IO

MSDN: Common I/O tasks.

Create a text file:
File.CreateText method
FileInfo.CreateText method
File.Create method
FileInfo.Create method

Append text to a file
File.AppendText method
FileInfo.AppendText method

Rename or move a file
File.Move method
FileInfo.MoveTo method

Delete a file
File.Delete method
FileInfo.Delete method

Copy a file
File.Copy method
FileInfo.CopyTo method

Get the size of a file
FileInfo.Length property

Get the attributes of a file
File.GetAttributes method

Set the attributes of a file
File.SetAttributes method

Determine whether a file exists
File.Exists method

Retrieve a file name extension
Path.GetExtension method

Retrieve the fully qualified path of a file
Path.GetFullPath method

Retrieve the file name and extension from a path
Path.GetFileName method

Change the extension of a file
Path.ChangeExtension method

Common Directory Tasks

Create a directory
Directory.CreateDirectory method
FileInfo.Directory property

Create a subdirectory
DirectoryInfo.CreateSubdirectory method

Rename or move a directory
Directory.Move method
DirectoryInfo.MoveTo method

Delete a directory
Directory.Delete method
DirectoryInfo.Delete method

Determine whether a directory exists
Directory.Exists method   

Asynchronous IO


Starting with the .NET Framework 4.5, the I/O types include async methods to simplify asynchronous operations. An async method contains Async in its name, such as ReadAsync, WriteAsync, CopyToAsync, FlushAsync, ReadLineAsync, and ReadToEndAsync. These async methods are implemented on stream classes, such as Stream, FileStream, and MemoryStream, and on classes that are used for reading from or writing to streams, such TextReader and TextWriter.

Iterate through a directory tree

string[] drives = System.Environment.GetLogicalDrives();

foreach (string dr in drives) {
    System.IO.DriveInfo di = new System.IO.DriveInfo(dr);
    System.IO.DirectoryInfo rootDir = di.RootDirectory;

    files = root.GetFiles("*.*");
// This is thrown if even one of the files requires permissions greater
// than the application provides.
catch (UnauthorizedAccessException e)
    // This code just writes out the message and continues to recurse.
    // You may decide to do something different here. For example, you
    // can try to elevate your privileges and access the file again.
catch (System.IO.DirectoryNotFoundException e)

if (files != null)
    foreach (System.IO.FileInfo fi in files)
        // In this example, we only access the existing FileInfo object. If we
        // want to open, delete or modify the file, then
        // a try-catch block is required here to handle the case
        // where the file has been deleted since the call to TraverseTree().

    // Now find all the subdirectories under this directory.
    subDirs = root.GetDirectories();


class ReadFromFile
    static void Main()
        // Read the file as one string.
        string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");

        // Read each line of the file into a string array. Each element of the array is one line of the file.
        string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");

class WriteFile
    static void Main()
        string[] lines = { "First line", "Second line", "Third line" };
        System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);

        string text = "A class is the most powerful data type in C#. Like a structure, " +
                       "a class defines the data and behavior of the data type. ";
        System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text);

        using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt"))
            foreach (string line in lines)
                // If the line doesn't contain the word 'Second', write the line to the file.
                if (!line.Contains("Second"))

        // Append new text to an existing file.
        using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
            file.WriteLine("Fourth line");



The value of path.directorySeparatorChar field is a backslash ('/') on UNIX, and a slash ('\') on Windows and Macintosh operating systems.


foreach (char c in Path.GetInvalidPathChars())
// This code produces output similar to the following:
// Note that the InvalidPathCharacters contain characters
// outside of the printable character set.
// Path.AltDirectorySeparatorChar=/
// Path.DirectorySeparatorChar=\
// Path.PathSeparator=;
// Path.VolumeSeparatorChar=:


MSDN: Path.GetDirectoryName.

Passing the path "C:\Directory\SubDirectory\test.txt" into the GetDirectoryName method will return "C:\Directory\SubDirectory". Passing that string, "C:\Directory\SubDirectory", into GetDirectoryName will result in "C:\Directory".

string filePath = @"C:\MyDir\MySubDir\myfile.ext";
string directoryName;
int i = 0;

while (filePath != null)
    directoryName = Path.GetDirectoryName(filePath);
    Console.WriteLine("GetDirectoryName('{0}') returns '{1}'",
        filePath, directoryName);
    filePath = directoryName;
    if (i == 1)
        filePath = directoryName + @"\";  // this will preserve the previous path
This code produces the following output:

GetDirectoryName('C:\MyDir\MySubDir\myfile.ext') returns 'C:\MyDir\MySubDir'
GetDirectoryName('C:\MyDir\MySubDir') returns 'C:\MyDir'
GetDirectoryName('C:\MyDir\') returns 'C:\MyDir'
GetDirectoryName('C:\MyDir') returns 'C:\'
GetDirectoryName('C:\') returns ''

The inner call to GetDirectoryName will return the full path, while the outer call to GetFileName() will return the last path component - which will be the folder name. SO: get the folder name from a path.

string path = "C:/folder1/folder2/file.txt";
string lastFolderName = Path.GetFileName( Path.GetDirectoryName( path ) ); // folder2


MSDN: Path.GetTempPath.

string result = Path.GetTempPath();

// This example produces output similar to the following.
// C:\Users\UserName\AppData\Local\Temp\


SO: Convert forward slashes to backslashes.

This function will normalize the path, e.g. change all "a/b" to "a\\b" so that string replacing can work.

Path.GetFullPath(Path.Combine("test1/test2", "test3\\test4"));

private void createIntermediateDir(string filePath)
    // Here we use Path.GetFullPath here to guarantee that all seps in the string is "\\" ignorant of user input. They might input '/' instead.
    string dstDir = Path.GetDirectoryName(filePath).Replace(Path.GetFullPath(_config.srcRootDir), Path.GetFullPath(_config.dstRootDir));