15. Files, Streams and Directories
The System.IO namespace is how C# works with files and folders. There are two levels. The high-level static classes File (create, read, write, copy, move, delete) and Directory (create, list, delete folders) do a whole job in one call and are right for small files. The object versions FileInfo and DirectoryInfo describe one file or folder with properties such as Name, Length, Extension, CreationTime and Exists. The Path class builds and takes apart paths safely (Path.Combine, GetFileName, GetExtension) and works on every operating system.
The low-level tool is the stream: an ordered flow of bytes you read or write piece by piece, which suits large files. FileStream reads and writes raw bytes. You open it with a FileMode (what to do if the file exists or not: CreateNew, Create, Open, OpenOrCreate, Truncate, Append), a FileAccess (Read, Write, ReadWrite) and a FileShare (what other programs may do meanwhile: None, Read, Write, ReadWrite). On top of a stream you put a reader or writer: StreamReader and StreamWriter for text (ReadLine, ReadToEnd, Write, WriteLine) and BinaryReader and BinaryWriter for primitive values (int, double, bool, string) stored in compact binary form. MemoryStream is a stream that lives in memory.
Always release files: wrap streams, readers and writers in using so they are flushed and closed even when an error occurs. Expect failures (FileNotFoundException, DirectoryNotFoundException, UnauthorizedAccessException, IOException when a file is in use) and handle them. Relative paths are relative to the program's current directory, not to the source file. For structured data, text formats such as CSV and JSON (System.Text.Json) are the usual choice, and every read/write API has an async version (ReadAllTextAsync, WriteLineAsync, CopyToAsync) which web applications should prefer.
- The Path class
- File class: write, read, append, copy, move, delete
- WriteAllLines, ReadLines and bytes
- FileInfo
- Directory class
- DirectoryInfo and FileInfo together
- Current directory, special folders and temp files
- FileStream: writing and reading bytes
- FileMode in action
- FileAccess and FileShare
- Seeking inside a FileStream
- StreamWriter and StreamReader
- StreamReader: Read, Peek, ReadLine, ReadToEnd
- Appending to a log file
- BinaryWriter and BinaryReader
- Binary file with a list of numbers
- MemoryStream
- Text encodings
- Handling file errors
- Writing and reading CSV
- Saving objects as JSON
- Async file reading and writing
- Copying a file with a buffer
- Saving an uploaded file in ASP.NET Core
Key points to remember
- Use File.ReadAllText / WriteAllText / ReadAllLines / AppendAllText for small files; use StreamReader / StreamWriter or File.ReadLines for large or line-by-line work, because ReadAll* loads the whole file into memory.
- File.WriteAllText replaces any existing content. To add to the end use File.AppendAllText, or new StreamWriter(path, append: true), or FileMode.Append.
- FileMode: CreateNew (error if it exists), Create (new or overwrite), Open (error if missing), OpenOrCreate, Truncate (open and empty it), Append (open and go to the end; write-only).
- Always build paths with Path.Combine (not string +) so the correct separator is used (\ on Windows, / on Linux and macOS).
- Check first with File.Exists / Directory.Exists, but still use try/catch: the file can change between the check and the use.
- StreamWriter buffers data. Disposing (using) flushes and closes it. Call Flush() if you need data written immediately.
- BinaryReader must read values in exactly the same order and types they were written by BinaryWriter.
- Text encoding: UTF-8 is the default and the best choice. A file written in one encoding and read in another shows garbled characters.
- In ASP.NET Core never trust uploaded file names: use Path.GetFileName, check the extension and size, and store files outside folders that execute code. Use IWebHostEnvironment.WebRootPath or ContentRootPath for locations.
- Never delete or write outside the folders your app owns, and be careful with Directory.Delete(path, true): it removes everything inside.
Example 1: The Path class
string path = "/data/reports/sales.txt";
Console.WriteLine(Path.GetFileName(path));
Console.WriteLine(Path.GetFileNameWithoutExtension(path));
Console.WriteLine(Path.GetExtension(path));
Console.WriteLine(Path.ChangeExtension("sales.txt", ".csv"));
Console.WriteLine(Path.HasExtension("README"));
Console.WriteLine(Path.IsPathRooted(path));
string combined = Path.Combine("data", "reports", "sales.txt");
Console.WriteLine(combined); // data/reports/sales.txt (data\reports\sales.txt on Windows)
Show output
Outputsales.txt sales .txt sales.csv False True data/reports/sales.txt
Example 2: File class: write, read, append, copy, move, delete
string path = "notes.txt";
File.WriteAllText(path, "First line\n"); // creates or overwrites
File.AppendAllText(path, "Second line\n");
File.AppendAllLines(path, new[] { "Third", "Fourth" });
string all = File.ReadAllText(path);
string[] lines = File.ReadAllLines(path);
Console.WriteLine(lines.Length);
Console.WriteLine(lines[2]);
Console.WriteLine(File.Exists(path));
File.Copy(path, "copy.txt", overwrite: true);
File.Move("copy.txt", "moved.txt", overwrite: true);
Console.WriteLine(File.Exists("copy.txt") + " " + File.Exists("moved.txt"));
File.Delete("moved.txt");
Console.WriteLine(File.Exists("moved.txt"));
Show output
Output4 Third True False True False
Example 3: WriteAllLines, ReadLines and bytes
File.WriteAllLines("names.txt", new[] { "Ann", "Ben", "Cleo" });
foreach (string line in File.ReadLines("names.txt")) // reads one line at a time
Console.WriteLine(line.ToUpper());
Console.WriteLine(File.ReadLines("names.txt").Count(n => n.Length > 3));
File.WriteAllBytes("raw.bin", new byte[] { 1, 2, 3 });
byte[] bytes = File.ReadAllBytes("raw.bin");
Console.WriteLine(bytes.Length + " " + bytes[2]);
Show output
OutputANN BEN CLEO 1 3 3
Example 4: FileInfo
File.WriteAllText("info.txt", "Hello");
var info = new FileInfo("info.txt");
Console.WriteLine(info.Name);
Console.WriteLine(info.Extension);
Console.WriteLine(info.Exists);
Console.WriteLine(info.Length); // size in bytes
Console.WriteLine(info.IsReadOnly);
Console.WriteLine(info.LastWriteTime > DateTime.Now.AddMinutes(-1));
info.CopyTo("info-backup.txt", true);
info.Delete();
Console.WriteLine(File.Exists("info-backup.txt"));
Show output
Outputinfo.txt .txt True 5 False True True
Example 5: Directory class
Directory.CreateDirectory("demo/sub"); // creates every missing folder
File.WriteAllText("demo/a.txt", "A");
File.WriteAllText("demo/b.log", "B");
File.WriteAllText("demo/sub/c.txt", "C");
Console.WriteLine(Directory.Exists("demo"));
foreach (string f in Directory.GetFiles("demo").OrderBy(x => x))
Console.WriteLine(Path.GetFileName(f));
Console.WriteLine(Directory.GetFiles("demo", "*.txt").Length);
Console.WriteLine(Directory.GetFiles("demo", "*.txt", SearchOption.AllDirectories).Length);
Console.WriteLine(Directory.GetDirectories("demo").Length);
Directory.Delete("demo", recursive: true); // removes the folder and its contents
Console.WriteLine(Directory.Exists("demo"));
Show output
OutputTrue a.txt b.log 1 2 1 False
Example 6: DirectoryInfo and FileInfo together
var dir = new DirectoryInfo("demo2");
dir.Create();
File.WriteAllText(Path.Combine(dir.FullName, "x.txt"), "12345");
File.WriteAllText(Path.Combine(dir.FullName, "y.txt"), "123");
foreach (FileInfo fi in dir.GetFiles().OrderBy(f => f.Name))
Console.WriteLine($"{fi.Name} {fi.Length} bytes");
long total = dir.EnumerateFiles().Sum(f => f.Length);
Console.WriteLine("Total: " + total);
Console.WriteLine(dir.Name);
dir.Delete(true);
Console.WriteLine(Directory.Exists("demo2"));
Show output
Outputx.txt 5 bytes y.txt 3 bytes Total: 8 demo2 False
Example 7: Current directory, special folders and temp files
Console.WriteLine(Directory.GetCurrentDirectory() == Environment.CurrentDirectory);
string temp = Path.GetTempPath();
Console.WriteLine(Directory.Exists(temp));
string tempFile = Path.GetTempFileName(); // creates an empty unique file
File.WriteAllText(tempFile, "temporary");
Console.WriteLine(File.ReadAllText(tempFile));
File.Delete(tempFile);
string docs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Console.WriteLine(docs.Length >= 0);
string fullPath = Path.GetFullPath("notes.txt"); // relative to the current directory
Console.WriteLine(Path.IsPathRooted(fullPath));
Show output
OutputTrue True temporary True True
Example 8: FileStream: writing and reading bytes
using System.Text;
using (var fs = new FileStream("data.bin", FileMode.Create, FileAccess.Write))
{
byte[] bytes = { 72, 105, 33 }; // the letters "Hi!"
fs.Write(bytes, 0, bytes.Length);
} // closed and flushed here
using (var fs = new FileStream("data.bin", FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[fs.Length];
int read = fs.Read(buffer, 0, buffer.Length);
Console.WriteLine(read);
Console.WriteLine(Encoding.UTF8.GetString(buffer));
Console.WriteLine(fs.Length);
Console.WriteLine(fs.Position); // now at the end
}
Show output
Output3 Hi! 3 3
Example 9: FileMode in action
File.WriteAllText("log.txt", "A");
using (var fs = new FileStream("log.txt", FileMode.Append)) // goes to the end
using (var writer = new StreamWriter(fs))
{
writer.Write("B");
}
Console.WriteLine(File.ReadAllText("log.txt"));
try { new FileStream("log.txt", FileMode.CreateNew).Dispose(); }
catch (IOException) { Console.WriteLine("CreateNew fails if the file exists"); }
try { new FileStream("missing.txt", FileMode.Open); }
catch (FileNotFoundException) { Console.WriteLine("Open fails if the file is missing"); }
using (var fs = new FileStream("log.txt", FileMode.Truncate)) // empties the file
Console.WriteLine(fs.Length);
using (var fs = new FileStream("new.txt", FileMode.OpenOrCreate))
Console.WriteLine(fs.Length);
Show output
OutputAB CreateNew fails if the file exists Open fails if the file is missing 0 0
Example 10: FileAccess and FileShare
using var first = new FileStream("lock.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None);
try
{
using var second = new FileStream("lock.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
}
catch (IOException)
{
Console.WriteLine("File is locked by another stream");
}
File.WriteAllText("ro.txt", "x");
using (var readOnly = new FileStream("ro.txt", FileMode.Open, FileAccess.Read))
{
Console.WriteLine(readOnly.CanRead + " " + readOnly.CanWrite);
}
Show output
OutputFile is locked by another stream True False
Example 11: Seeking inside a FileStream
using var fs = new FileStream("seek.bin", FileMode.Create, FileAccess.ReadWrite);
fs.Write(new byte[] { 1, 2, 3, 4, 5 });
fs.Seek(2, SeekOrigin.Begin); // 2 bytes from the start
Console.WriteLine(fs.ReadByte());
fs.Seek(-1, SeekOrigin.End); // 1 byte before the end
Console.WriteLine(fs.ReadByte());
fs.Position = 0;
fs.WriteByte(99); // overwrite the first byte
fs.Position = 0;
Console.WriteLine(fs.ReadByte());
Console.WriteLine(fs.Length);
Show output
Output3 5 99 5
Example 12: StreamWriter and StreamReader
using (var writer = new StreamWriter("people.txt"))
{
writer.WriteLine("Ann,30");
writer.WriteLine("Ben,25");
writer.Write("Cleo");
writer.Write(",41");
}
using (var reader = new StreamReader("people.txt"))
{
string? line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(',');
Console.WriteLine($"{parts[0]} is {parts[1]}");
}
}
Show output
OutputAnn is 30 Ben is 25 Cleo is 41
Example 13: StreamReader: Read, Peek, ReadLine, ReadToEnd
File.WriteAllText("t.txt", "ab\ncd");
using var r = new StreamReader("t.txt");
Console.WriteLine((char)r.Read()); // reads one character: a
Console.WriteLine((char)r.Peek()); // looks at the next without consuming it: b
Console.WriteLine(r.ReadLine()); // the rest of the line
Console.WriteLine(r.EndOfStream);
Console.WriteLine(r.ReadToEnd()); // everything that is left
Console.WriteLine(r.EndOfStream);
Show output
Outputa b b False cd True
Example 14: Appending to a log file
using System.Text;
using (var w = new StreamWriter("app.log", append: false, Encoding.UTF8))
w.WriteLine("Start");
for (int i = 1; i <= 2; i++)
{
using var w = new StreamWriter("app.log", append: true); // add to the end
w.WriteLine($"Entry {i}");
}
foreach (string line in File.ReadAllLines("app.log"))
Console.WriteLine(line);
// Tip: new StreamWriter(path) { AutoFlush = true } writes every call immediately,
// which is useful for logs that must survive a crash.
Show output
OutputStart Entry 1 Entry 2
Example 15: BinaryWriter and BinaryReader
using (var bw = new BinaryWriter(File.Open("scores.dat", FileMode.Create)))
{
bw.Write("Ann"); // string (length-prefixed)
bw.Write(95); // int, 4 bytes
bw.Write(88.5); // double, 8 bytes
bw.Write(true); // bool, 1 byte
}
using (var br = new BinaryReader(File.Open("scores.dat", FileMode.Open)))
{
string name = br.ReadString(); // same order as written
int mark = br.ReadInt32();
double average = br.ReadDouble();
bool passed = br.ReadBoolean();
Console.WriteLine($"{name} {mark} {average} {passed}");
}
Console.WriteLine(new FileInfo("scores.dat").Length);
Show output
OutputAnn 95 88.5 True 17
Example 16: Binary file with a list of numbers
int[] data = { 10, 20, 30 };
using (var bw = new BinaryWriter(File.Create("ints.dat")))
{
bw.Write(data.Length); // store the count first
foreach (int n in data) bw.Write(n);
}
using var br = new BinaryReader(File.OpenRead("ints.dat"));
int count = br.ReadInt32();
var back = new List<int>();
for (int i = 0; i < count; i++)
back.Add(br.ReadInt32());
Console.WriteLine(string.Join(",", back));
Console.WriteLine(br.BaseStream.Length); // 4 + 3 * 4 bytes
Show output
Output10,20,30 16
Example 17: MemoryStream
using var ms = new MemoryStream();
var writer = new StreamWriter(ms);
writer.Write("in memory");
writer.Flush(); // push buffered text into the stream
Console.WriteLine(ms.Length);
ms.Position = 0; // go back to the start to read
Console.WriteLine(new StreamReader(ms).ReadToEnd());
ms.Position = 0;
using (var fs = File.Create("mem.txt"))
ms.CopyTo(fs); // copy one stream into another
Console.WriteLine(File.ReadAllText("mem.txt"));
Show output
Output9 in memory in memory
Example 18: Text encodings
using System.Text;
Console.WriteLine(Encoding.UTF8.GetBytes("A").Length);
Console.WriteLine(Encoding.UTF8.GetBytes("é").Length); // accents need 2 bytes
Console.WriteLine(Encoding.Unicode.GetBytes("A").Length); // UTF-16: 2 bytes
File.WriteAllText("utf8.txt", "café"); // UTF-8 without a BOM by default
Console.WriteLine(File.ReadAllText("utf8.txt", Encoding.UTF8));
Console.WriteLine(new FileInfo("utf8.txt").Length);
Show output
Output1 2 2 café 5
Example 19: Handling file errors
static void ReadFile(string path)
{
try
{
Console.WriteLine(File.ReadAllText(path).Length);
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found");
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("Folder not found");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("No permission");
}
catch (IOException ex) // general I/O errors go last
{
Console.WriteLine("I/O error: " + ex.Message);
}
}
ReadFile("does-not-exist.txt");
ReadFile("no-such-folder/file.txt");
Show output
OutputFile not found Folder not found
Example 20: Writing and reading CSV
File.WriteAllLines("sales.csv", new[]
{
"Item,Qty,Price",
"Pen,10,5",
"Book,2,50",
"Bag,1,300"
});
decimal total = 0;
foreach (string line in File.ReadLines("sales.csv").Skip(1)) // skip the header
{
string[] c = line.Split(',');
int qty = int.Parse(c[1]);
decimal price = decimal.Parse(c[2]);
total += qty * price;
}
Console.WriteLine(total);
File.WriteAllText("total.txt", $"Total: {total}");
Console.WriteLine(File.ReadAllText("total.txt"));
Show output
Output450 Total: 450
Example 21: Saving objects as JSON
using System.Text.Json;
var person = new Person("Ann", 30, new[] { "C#", "SQL" });
string json = JsonSerializer.Serialize(person);
Console.WriteLine(json);
File.WriteAllText("person.json", json);
var back = JsonSerializer.Deserialize<Person>(File.ReadAllText("person.json"));
Console.WriteLine(back!.Name + " " + back.Skills.Length);
var pretty = new JsonSerializerOptions { WriteIndented = true };
Console.WriteLine(JsonSerializer.Serialize(new { Id = 1, Active = true }, pretty));
record Person(string Name, int Age, string[] Skills);
Show output
Output{"Name":"Ann","Age":30,"Skills":["C#","SQL"]}
Ann 2
{
"Id": 1,
"Active": true
}
Example 22: Async file reading and writing
await using (var w = new StreamWriter("async.txt"))
{
await w.WriteLineAsync("Line A");
await w.WriteLineAsync("Line B");
}
using var r = new StreamReader("async.txt");
string? first = await r.ReadLineAsync();
string rest = await r.ReadToEndAsync();
Console.WriteLine(first);
Console.WriteLine(rest.Trim());
Show output
OutputLine A Line B
Example 23: Copying a file with a buffer
File.WriteAllBytes("source.bin", new byte[10_000]);
using (var input = File.OpenRead("source.bin"))
using (var output = File.Create("target.bin"))
{
byte[] buffer = new byte[4096];
int read;
int chunks = 0;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
chunks++;
}
Console.WriteLine(chunks);
}
Console.WriteLine(new FileInfo("target.bin").Length);
Show output
Output3 10000
Example 24: Saving an uploaded file in ASP.NET Core
[HttpPost]
public async Task<IActionResult> Upload(IFormFile file, [FromServices] IWebHostEnvironment env)
{
if (file == null || file.Length == 0) return BadRequest("No file");
if (file.Length > 5_000_000) return BadRequest("File too large");
string ext = Path.GetExtension(file.FileName).ToLower();
if (ext != ".pdf" && ext != ".png") return BadRequest("Type not allowed");
string folder = Path.Combine(env.WebRootPath, "uploads");
Directory.CreateDirectory(folder);
string safeName = Guid.NewGuid() + ext; // never trust the client's name
string path = Path.Combine(folder, safeName);
using var stream = new FileStream(path, FileMode.Create);
await file.CopyToAsync(stream);
return Ok("Saved " + safeName);
}
Show output
Output(runs inside a web request; the file is saved in wwwroot/uploads) Response body: Saved 3f2a...c1.pdf