All articles
2 min read

Handy C# Code Snippets for Developers

Practical C# snippets for WinForms rounded windows, ZIP file handling, file I/O, async HTTP requests, string operations, and LINQ — ready to copy into your projects.

A collection of practical C# snippets for common tasks. Each covers a pattern that comes up often in desktop apps, utilities, and backend code.

Rounded WinForms Window

Create a Windows Form with rounded corners using P/Invoke to call the Win32 CreateRoundRectRgn function:

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public partial class Form1 : Form
{
    [DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
    private static extern IntPtr CreateRoundRectRgn(
        int nLeftRect, int nTopRect,
        int nRightRect, int nBottomRect,
        int nWidthEllipse, int nHeightEllipse
    );

    public Form1()
    {
        InitializeComponent();
        FormBorderStyle = FormBorderStyle.None;
        Region = System.Drawing.Region.FromHrgn(
            CreateRoundRectRgn(0, 0, Width, Height, 20, 20)
        );
    }
}

For modern Windows apps, consider WinUI 3 or using CornerRadius in XAML-based frameworks, which avoids P/Invoke entirely.

ZIP File Creation and Extraction

using System.IO;
using System.IO.Compression;

// Create a ZIP from a directory
ZipFile.CreateFromDirectory(@"C:\source-folder", @"C:\archive.zip");

// Extract a ZIP to a directory
ZipFile.ExtractToDirectory(@"C:\archive.zip", @"C:\extracted");

// Add a single file to an existing ZIP
using var archive = ZipFile.Open(@"C:\archive.zip", ZipArchiveMode.Update);
archive.CreateEntryFromFile(@"C:\file.txt", "file.txt");

Add a reference to System.IO.Compression.ZipFile via NuGet if needed.

File Reading and Writing

// Read all text
string content = File.ReadAllText("data.txt");

// Read lines as array
string[] lines = File.ReadAllLines("data.txt");

// Write text (overwrite)
File.WriteAllText("output.txt", "Hello, World!");

// Append text
File.AppendAllText("log.txt", $"{DateTime.Now}: event occurred\n");

// Read large file line by line (memory-efficient)
foreach (string line in File.ReadLines("large-file.txt"))
{
    Console.WriteLine(line);
}

Async HTTP Request

using System.Net.Http;
using System.Text.Json;

var httpClient = new HttpClient();

// GET request
var response = await httpClient.GetAsync("https://api.example.com/data");
response.EnsureSuccessStatusCode();
string json = await response.Content.ReadAsStringAsync();

// POST JSON
var payload = new { Name = "Alice", Age = 30 };
var jsonContent = new StringContent(
    JsonSerializer.Serialize(payload),
    System.Text.Encoding.UTF8,
    "application/json"
);
var postResponse = await httpClient.PostAsync("https://api.example.com/users", jsonContent);

Use a single HttpClient instance per application (or via IHttpClientFactory) — creating one per request exhausts socket connections.

String Operations

string s = "  Hello, World!  ";

// Common methods
s.Trim()                    // "Hello, World!"
s.ToUpper()                 // "  HELLO, WORLD!  "
s.Replace("World", "C#")   // "  Hello, C#!  "
s.Contains("World")        // true
s.StartsWith("  Hello")    // true
s.Split(", ")               // ["  Hello", "World!  "]
s.Substring(8, 5)           // "World" (start index, length)

// String interpolation
string name = "Alice";
int age = 30;
string msg = $"Name: {name}, Age: {age}";

// Raw string literals (C# 11+)
string json = """
    {
      "key": "value"
    }
    """;

LINQ Examples

using System.Linq;

var numbers = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// Filter, transform, collect
var evenSquares = numbers
    .Where(n => n % 2 == 0)
    .Select(n => n * n)
    .ToList();
// [4, 16, 36, 64, 100]

// Aggregate
int sum = numbers.Sum();         // 55
int max = numbers.Max();         // 10
double avg = numbers.Average();  // 5.5

// Grouping
var words = new[] { "apple", "banana", "avocado", "blueberry" };
var grouped = words.GroupBy(w => w[0])
                   .ToDictionary(g => g.Key, g => g.ToList());
// {'a': ["apple","avocado"], 'b': ["banana","blueberry"]}

// First/single with conditions
var first = numbers.FirstOrDefault(n => n > 5);   // 6 (returns 0 if none)

Conclusion

These snippets cover the day-to-day patterns in C# development. For modern .NET (6+), prefer async/await throughout, use using declarations (without braces) for cleaner IDisposable handling, and target nullable reference types (#nullable enable) to catch null-related bugs at compile time.