Skip to content

EN CSharp Files JSON

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

Files, streams and JSON

Manual C# · Examples UO

System.IO provides files, directories and streams. Path.Combine connects paths, File works with whole content, Stream works with a sequence of bytes. The encoding determines how the text is converted. For asynchronous operations, pass a cancellation token.

Simple example (Example.cs)

Save this example separately as Example.cs. Run it independently of the other examples on this page.

Example.cs:

// PROJECT-EXAMPLE
var counts = new int[] { 2, 3 };
string json = System.Text.Json.JsonSerializer.Serialize(counts);
System.Console.WriteLine(json);

Result:

[2,3]
using System.IO;
using System.Text;
string file = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".txt");
try
{
    await File.WriteAllTextAsync(file, "C# text", Encoding.UTF8, Cancellation);
    string text = await File.ReadAllTextAsync(file, Encoding.UTF8, Cancellation);
    UO.Print(text);
}
finally
{
    if (File.Exists(file)) File.Delete(file);
}
record Settings(int Delay, string Mode);
var settings = new Settings(100, "idle");
string json = System.Text.Json.JsonSerializer.Serialize(settings);
Settings? restored = System.Text.Json.JsonSerializer.Deserialize<Settings>(json);
UO.Print(restored?.Mode ?? "missing");

The relative path depends on the process's working directory. JSON stores data and does not execute C# code. Choose a serialization that suits your properties, constructors, and naming settings.

Official Documentation: Files, Streams, and JSON - Microsoft Learn.

Clone this wiki locally