C# Files

C# Files

Working with files is a critical skill for any developer. You will often need your programs to read configuration data from a file or write user data to save it permanently.

The File class from the System.IO namespace allows us to work with files in C#.


The System.IO Namespace

To use the File class, you must include the System.IO namespace at the top of your file.

The File class offers many useful, built-in methods, such as:


Writing and Reading Files

Let's look at a complete example of creating a file, writing some text into it, and then reading it back into the console.

Example: Write and Read File

using System;
using System.IO;  // Include the System.IO namespace

class Program { static void Main(string[] args) { string writeText = "Hello World! Writing to files is fun."; // Text to write string filePath = "filename.txt"; // 1. Write the text to a file. // (This creates the file if it doesn't exist, or overwrites it if it does). File.WriteAllText(filePath, writeText); Console.WriteLine("Successfully wrote to the file."); // 2. Read the contents of the file string readText = File.ReadAllText(filePath); // 3. Output the contents to the console Console.WriteLine("File Contents:"); Console.WriteLine(readText); } }

Handling Missing Files

When dealing with files, things can occasionally go wrong. The file you are trying to read might not exist, or you might not have permission to access it!

If you try to read a file that doesn't exist, C# will throw a FileNotFoundException and crash your program. To prevent this, always check if the file exists using File.Exists(path) before attempting to read it, or use try..catch blocks (which we will learn in the next lesson!).

Example: Checking if a File Exists

using System;
using System.IO;

class Program { static void Main(string[] args) { if (File.Exists("filename.txt")) { string content = File.ReadAllText("filename.txt"); Console.WriteLine(content); } else { Console.WriteLine("File not found!"); } } }


Exercise

?

Which namespace must be included to use the File class in C#?