C# Files

C# Tutorial

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

ClassDescription
FileStatic class for basic file operations
FileInfoInstance class for detailed file info
StreamReaderRead text from files
StreamWriterWrite text to files
BinaryReaderRead binary files
BinaryWriterWrite binary files
DirectoryWork with folders/directories
PathManipulate 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 File and FileInfo for file operations

  • Use StreamReader / StreamWriter for reading/writing text

  • Always check if file exists before reading/deleting

  • Supports text, binary, append, and metadata operations

You may also like...