Read Text File
Demonstrates how to read a UTF‑8 text file using File.OpenRead and StreamReader.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = @"C:\Temp\sample.txt";
using (var reader = new StreamReader(path))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
}
}
Write JSON File
Creates a simple JSON configuration file using System.Text.Json.
using System;
using System.IO;
using System.Text.Json;
class Config
{
public string Name { get; set; }
public int Interval { get; set; }
}
class Program
{
static void Main()
{
var cfg = new Config { Name = "SampleApp", Interval = 30 };
string json = JsonSerializer.Serialize(cfg, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(@"C:\Temp\config.json", json);
Console.WriteLine("Config written.");
}
}
Read Registry Value
Retrieves a string value from HKCU\Software\MyApp using Microsoft.Win32.Registry.
using Microsoft.Win32;
using System;
class Program
{
static void Main()
{
using (var key = Registry.CurrentUser.OpenSubKey(@"Software\MyApp"))
{
if (key != null)
{
var value = key.GetValue("InstallPath") as string;
Console.WriteLine($"InstallPath: {value}");
}
else
{
Console.WriteLine("Key not found.");
}
}
}
}
SQLite Query
Executes a SELECT query against a local SQLite database using Microsoft.Data.Sqlite.
using Microsoft.Data.Sqlite;
using System;
class Program
{
static void Main()
{
var connectionString = @"Data Source=C:\Temp\sample.db";
using (var connection = new SqliteConnection(connectionString))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = "SELECT Id, Name FROM Users WHERE Active = 1;";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine($"{reader.GetInt32(0)} – {reader.GetString(1)}");
}
}
}
}
}
Parse XML Document
Loads an XML file and extracts values using XDocument.
using System;
using System.Linq;
using System.Xml.Linq;
class Program
{
static void Main()
{
var doc = XDocument.Load(@"C:\Temp\data.xml");
var items = doc.Root.Elements("Item")
.Select(x => new
{
Id = (int)x.Element("Id"),
Name = (string)x.Element("Name")
});
foreach (var item in items)
{
Console.WriteLine($"{item.Id}: {item.Name}");
}
}
}