C# Files
C# Files
In C#, file handling allows you to read, write, and manipulate files on the disk.
C# provides classes in the System.IO namespace for file operations.
Common File Classes in System.IO
| Class | Description |
|---|---|
File |
Static class for basic file operations |
FileInfo |
Instance class for detailed file info |
StreamReader |
Read text from files |
StreamWriter |
Write text to files |
BinaryReader |
Read binary files |
BinaryWriter |
Write binary files |
Directory |
Work with folders/directories |
Path |
Manipulate file/folder paths |
Writing to a File
Using File.WriteAllText
Using StreamWriter
Reading from a File
Using File.ReadAllText
Using StreamReader
Appending to a File
File Info
Checking File Existence
Deleting a File
Common Mistakes
❌ Forgetting to include System.IO namespace
❌ Not using using statement (can cause file locks)
❌ Ignoring exceptions (use try-catch)
Summary
-
Use
FileandFileInfofor file operations -
Use
StreamReader/StreamWriterfor reading/writing text -
Always check if file exists before reading/deleting
-
Supports text, binary, append, and metadata operations
