C# File Handling

What is File Handling?

File handling allows your program to store data permanently in files and read it later.

This is important for saving user data, logs, or application settings.

Loading...
Output:

Writing to a File

You can write data to a file using methods like WriteAllText or StreamWriter.

If the file does not exist, it will be created automatically.

Loading...
Output:

Reading from a File

Use ReadAllText or StreamReader to read file content.

Always ensure the file exists before reading.

Loading...
Output:

Appending to a File

Appending allows you to add content to a file without deleting existing data.

This is useful for logs or continuous data storage.

Loading...
Output:

Using StreamWriter

StreamWriter gives more control when writing to files.

You should always close it after use or use a using block.

Loading...
Output:

Using StreamReader

StreamReader allows reading files line by line.

This is useful for large files.

Loading...
Output:

Checking if a File Exists

Before reading a file, it is good practice to check if it exists.

Loading...
Output:

Handling Exceptions

File operations can fail due to missing files or permission issues.

Use try-catch to handle errors safely.

Loading...
Output:

Why File Handling is Important

File handling is used in almost every real-world application.

  • Saving user data
  • Logging system activity
  • Reading configuration files

Practice

Create a program that writes names to a file, reads them, and prints them.

Loading...
Output:

Need Help?