The System.IO namespace provides file and stream APIs—File, StreamReader, and async variants. Use using declarations so streams dispose even when exceptions throw—RAII-like discipline without manual fclose in C.
Read and write text
await File.WriteAllTextAsync("demo.txt", "hello\n");
string text = await File.ReadAllTextAsync("demo.txt");
For large files, stream line-by-line instead of loading entire contents into memory.
Streams
using var reader = new StreamReader("demo.txt");
string? line = await reader.ReadLineAsync();
Important interview questions and answers
- Q: File vs Stream?
A:Filestatic helpers for common cases; streams give fine-grained control and composability. - Q: Async file I/O benefits?
A:ReadAllTextAsyncavoids blocking thread pool threads during disk/network latency.
Self-check
- What ensures a StreamReader closes?
- When prefer streaming over ReadAllText?
Tip: Wrap streams in using or await using—IDisposable ensures files close even when exceptions throw.
Interview prep
- File vs FileStream?
Filestatic helpers for common operations;FileStreamfor low-level read/write control and seeking.- async file I/O?
ReadAllTextAsyncandWriteAllTextAsyncavoid blocking threads during disk operations.