System.IO Namespace

Provides types that allow reading and writing files and data streams, and types that represent streams and file system objects.

Classes

Interfaces

Enums

Exceptions

Example Usage

Reading a Text File

using System; using System.IO; public class Example { public static void Main(string[] args) { try { // Specify the path to a text file. string path = @"C:\Users\Public\Documents\MyFile.txt"; // Create a StreamReader. using (StreamReader sr = new StreamReader(path)) { string line; // Read and display lines from the file until the end of the file is reached. while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } } catch (Exception e) { // Let the user know what went wrong. Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } } }

Writing to a Text File

using System; using System.IO; public class Example { public static void Main(string[] args) { try { // Specify the path to a text file. string path = @"C:\Users\Public\Documents\MyFile.txt"; // Create a StreamWriter. using (StreamWriter sw = new StreamWriter(path)) { sw.WriteLine("This is the first line."); sw.WriteLine("This is the second line."); sw.WriteLine("This is the third line."); } Console.WriteLine("Successfully wrote to the file."); } catch (Exception e) { // Let the user know what went wrong. Console.WriteLine("The file could not be written:"); Console.WriteLine(e.Message); } } }