Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
// StreamReader, StreamWriter, BinaryReader, BinaryWriter using System.IO; using System.Text; string dir = Path.Combine(Path.GetTempPath(), "io_demo"); Directory.CreateDirectory(dir); // --- StreamWriter / StreamReader --- string csvPath = Path.Combine(dir, "data.csv"); await using var writer = new StreamWriter(csvPath, append: false, Encoding.UTF8); await writer.WriteLineAsync("Id,Name,Score"); for (int i = 1; i <= 5; i++) await writer.WriteLineAsync($"{i},Student{i},{i * 18}"); // 'await using' calls DisposeAsync automatically await using var reader = new StreamReader(csvPath, Encoding.UTF8); string? header = await reader.ReadLineAsync(); Console.WriteLine($"Header: {header}"); while (await reader.ReadLineAsync() is { } row) Console.WriteLine($" Row: {row}"); // --- BinaryWriter / BinaryReader --- string binPath = Path.Combine(dir, "data.bin"); using (var bw = new BinaryWriter(File.OpenWrite(binPath))) { bw.Write(42); // int bw.Write(3.14); // double bw.Write("hello"); // length-prefixed string bw.Write(true); // bool } using (var br = new BinaryReader(File.OpenRead(binPath))) { Console.WriteLine(br.ReadInt32()); // 42 Console.WriteLine(br.ReadDouble()); // 3.14 Console.WriteLine(br.ReadString()); // hello Console.WriteLine(br.ReadBoolean()); // True } Directory.Delete(dir, recursive: true);
Result
Open