Skip to content
C#

File I/O

Read, write, append, copy, and JSON-serialize files with File and streams.

By EZ4Code Team
file-iojsonstream

Code

using System;
using System.IO;
using System.Text.Json;

// Write all text in one call
File.WriteAllText("note.txt", "hello world\n");

// Read all text
string text = File.ReadAllText("note.txt");
Console.WriteLine(text.Trim());

// Append
File.AppendAllText("note.txt", "second line\n");

// Read line by line lazily
foreach (var line in File.ReadLines("note.txt"))
    Console.WriteLine($"[line] {line}");

// JSON serialize/deserialize
var data = new { Name = "Alice", Age = 30 };
string json = JsonSerializer.Serialize(data);
File.WriteAllText("data.json", json);

var person = JsonSerializer.Deserialize<JsonElement>(json);
Console.WriteLine(person.GetProperty("Name").GetString());

// Async copy
async Task CopyAsync(string src, string dst)
{
    using var sIn = File.OpenRead(src);
    using var sOut = File.Create(dst);
    await sIn.CopyToAsync(sOut);
}
await CopyAsync("note.txt", "note.copy.txt");

Explanation

File provides one-shot helpers like ReadAllText, WriteAllText, and ReadLines that cover simple cases without managing streams. For larger or asynchronous work, OpenRead and OpenCreate return streams you can copy through CopyToAsync. System.Text.Json serializes objects to UTF-8 JSON without third-party libraries.

More C# Snippets