C# makes it easy to work with files: reading, writing, and creating them on your system.
📝 Writing to a File
1
2
3
using System.IO;
File.WriteAllText("hello.txt", "Hello, file!");
📖 Reading from a File
1
2
string text = File.ReadAllText("hello.txt");
Console.WriteLine(text); // "Hello, file!"
📄 Reading All Lines
Get all lines in a file as an array of strings:
1
2
3
4
5
string[] lines = File.ReadAllLines("hello.txt");
foreach (string line in lines)
{
Console.WriteLine(line);
}
⚠️ Error Handling
Always handle exceptions when working with files!
1
2
3
4
5
6
7
8
try
{
string data = File.ReadAllText("data.txt");
}
catch (IOException ex)
{
Console.WriteLine($"Problem reading file: {ex.Message}");
}
💡 Try It!
Write your name to a file, then read it back and print it.
1
2
File.WriteAllText("myname.txt", "Alex");
Console.WriteLine(File.ReadAllText("myname.txt"));
Next: Streams and advanced file I/O!