File Handling in C#
# CHAPTER 22
File Handling in C#
1. Introduction
When your C# program closes, all variables on the Stack and Heap are destroyed. If you want a user's high score or profile data to persist the next time they open the program, you must save it to the hard drive. File Handling via theSystem.IO namespace allows C# to read and write files permanently.
2. Learning Objectives
By the end of this chapter, you will be able to:-
Use the
System.IOnamespace.
-
Use the static
Fileclass for quick reads/writes.
-
Use
StreamWriterandStreamReaderfor handling large files.
- Understand basic file paths.
3. The Static File Class (The Easy Way)
For small text files, the File class provides extremely simple one-liners to read and write data.
4. Streams (StreamWriter / StreamReader)
If you are writing a massive log file (e.g., 500 MBs), using File.ReadAllText() will load the entire 500 MBs into your computer's RAM at once, potentially crashing the app.
Instead, we use Streams. Streams read/write data in small chunks (line by line).
5. The using Statement (Memory Management)
Notice the using statement in the block above? (This is different from using System; at the top of the file).
When you open a file, the Operating System locks it. If your program crashes before you manually call writer.Close(), the file remains locked! Wrapping file operations in a using block guarantees that the file is safely closed and disposed of, even if an exception occurs.
6. File Paths
-
Relative Path:
"notes.txt"saves the file exactly where the.exeis currently running from (usuallybin/Debug/net8.0/).
-
Absolute Path:
"C:\\Users\\Admin\\Desktop\\notes.txt"saves it to a specific hard drive location. Remember to use\\or verbatim strings@"C:\..."to avoid escape character errors.
7. Checking if a File Exists
Before reading a file, you should always check if it exists to prevent aFileNotFoundException.
8. Mini Project: Notes Manager
9. Common Mistakes
-
File In Use Error: Trying to read a file while a
StreamWriterstill holds it open. Always close writers or useusingblocks.
-
UnauthorizedAccessException: Trying to write a file to a protected system directory (like
C:\Windows) without administrator privileges.
10. Best Practices
-
Always wrap
StreamReaderandStreamWriterin ausingblock.
-
Always check
File.Exists()before attempting to read.
11. Exercises
-
1.
Write a program that asks the user for their name and age, and writes it to a file called
profile.txt.
-
2.
Write a program that reads
profile.txtand prints it to the console.
12. MCQs with Answers
Which namespace is required for file handling in C#?
Which static method reads an entire text file into a single string?
Which static method adds text to the end of an existing file?
Why should you use StreamReader instead of File.ReadAllText() for massive files?
What does wrapping a StreamWriter in a using block do?
How do you check if a file is actually on the hard drive before reading it?
What happens if you run File.WriteAllText("data.txt", "Hello"); but "data.txt" already exists?
What is the difference between a Relative Path and an Absolute Path?
How do you safely write a Windows path with backslashes in C#?
What property safely generates a newline character based on the current Operating System (Windows \r\n vs Linux \n)?
13. Interview Questions
-
Q: Explain the purpose of the
usingblock in the context ofIDisposableand file streams.
-
Q: Differentiate between
File.WriteAllText()andStreamWriter.
14. Summary
TheSystem.IO namespace gives your application persistence. For quick saves, the static File class is excellent. For large files or continuous logging, StreamWriter and StreamReader wrapped in using blocks guarantee safe, memory-efficient data streaming.