System.IO Namespace
Provides types that allow reading and writing files and data streams, and types that represent and operate on files and directories. This namespace includes classes for working with file system operations, streams, and data serialization.
Key Types
-
File
Provides static methods for the creation, copying, deletion, moving, and opening of files. It also provides methods for creating a Stream to a file, appending to a file, determining whether a file exists, and assisting in the creation of file streams.
-
Directory
Provides static methods for the creation, moving, and enumeration of directories and subdirectories. It also provides methods for obtaining the parent directory or drive of a path.
-
Stream
Abstract base class for all streams. A stream is a sequence of bytes, and a top-level stream abstractly manages this sequence of bytes. Streams can be used to read bytes from or write bytes to a storage medium such as a file, a network socket, or memory.
-
StreamReader
Implements a
TextReader
that reads characters from a byte stream in a particular encoding. -
StreamWriter
Implements a
TextWriter
for writing characters to a stream in a particular encoding. -
Path
Provides methods for creating, manipulating, and retrieving information about file and directory paths. This class is immutable.
-
FileInfo
Provides instance methods for the creation, copying, deletion, moving, and opening of files, and aids in their creation. This class is immutable.
-
DirectoryInfo
Provides instance methods for the creation, moving, and enumeration of directories and subdirectories. This class is immutable.
Common Operations
Example Usage: Reading a Text File
using System;
using System.IO;
public class Example
{
public static void Main(string[] args)
{
string filePath = "myFile.txt";
try
{
// Read the file line by line
using (StreamReader sr = new StreamReader(filePath))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}