File I/O
Read, write, append, copy, and JSON-serialize files with File and streams.
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
LINQ Query
Filter, project, sort, group, and aggregate sequences with LINQ.
Async and Await
Run I/O concurrently with async methods, await, and Task.WhenAll.
Properties
Encapsulate state with auto, computed, validated, and init-only properties.
Generics
Write type-parameterized methods and classes with constraints.
Delegates and Events
Define delegate types and publish events with safe subscription.
Reflection
Inspect type metadata and invoke members at runtime via System.Reflection.