File IO in C# comes down to three families of type. File and Directory are static helpers for one-line jobs. FileInfo and DirectoryInfo describe one item and are worth using when you ask several questions about the same file. Stream and its subclasses are for everything that is too big to hold in memory, or that is not a file at all.
Pick the smallest one that does the job. File.ReadAllText is the right answer surprisingly often, and a StreamReader is the right answer the moment the file is large enough that reading it all at once would hurt.
Never build a path by gluing strings together. Path.Combine exists because separators, trailing slashes and rooted paths behave differently on different platforms, and the Path class already knows the rules.
Everything we have written about files and streams is below.
Reading and Writing Files
Getting text and bytes in and out, including the fast way.
- StreamWriter and StreamReader
- Fastest Way to Read a Text File
- How to Read Data From a CSV File
- Different Ways to Overwrite a File
- Read a Text File Without Specifying the Full Path
- How to Save a List to a Text File
- How to Get the Number of Lines in a Text File
Paths, Files and Directories
Asking the file system questions, and moving things around.
- Path Class
- File and FileInfo Class
- Managing Directories With Directory and DirectoryInfo
- The File and Directory Classes
- Is a Path a File or a Directory
- How to Create a Temp File in the Temp Folder
- How to Rename Files in a Folder
- How to Get the Number of Files in a Folder
- Different Methods for Computing the Size of a Directory
- How to Compare Two Files
Streams
Working with data you do not want to load all at once.
CSV, Zip and File Formats
The formats that come up most often in business applications.
More File and IO Techniques
Watching for changes and the rest.
Where to Go Next
What usually happens to the data once it is loaded:
Wrap streams in a using statement. Between that and Path.Combine you avoid most of the file bugs that reach production.
