Provides static methods for the creation, copying, deletion, moving, and opening of files, and provides properties for creating and accessing elements of a file.
The exception that is thrown when a specified file or directory name or the a combination of file/directory names exceeds the system-defined maximum length.
Class
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);
}
}
}