C-SHARP - 5.2 System.IO

The System.IO namespace is one of the most important in the .NET framework. It groups together all the functionality for interacting with the file system: reading and writing files, working with data streams, handling input/output, and performing serialization and deserialization.

The main classes

  • File: a static class for creating, copying, moving, or deleting files, as well as reading or writing their content in a single operation.
  • Directory: the equivalent for directories — creation, moving, deletion, listing content.
  • Path: a utility for manipulating strings that represent a path (combining, extracting the extension, file name, etc.).
  • FileInfo and DirectoryInfo: object-oriented equivalents of File and Directory, preferable when chaining several operations on the same file.

Data streams: reading and writing

To process a file line by line or as a stream (useful for large files), System.IO offers the StreamReader and StreamWriter classes for text, as well as BinaryReader and BinaryWriter for binary data. These classes let you manage memory intelligently instead of loading everything at once.

To use System.IO, simply add the using System.IO; directive at the top of your file. In the next lessons, we'll explore each of these classes in detail with concrete examples of file and directory manipulation.