File I/O

    Lesson 14 • Expert Track

    Read and write files, manage directories, and work with JSON — essential skills for real-world C# applications.

    What You'll Learn

    • • Read and write text files with File.ReadAllText and File.WriteAllText
    • • Stream large files efficiently with StreamReader/StreamWriter
    • • Manage directories and use Path.Combine for safe paths
    • • Serialize and deserialize JSON with System.Text.Json
    • • Use using statements for automatic resource cleanup

    Real-World Analogy

    File.ReadAllText is like photocopying an entire document at once — quick but uses memory. StreamReader is like reading a book one page at a time — slower to start but efficient for 1,000-page novels. Choose the right approach based on file size.

    Running C# Locally: File I/O requires a local environment. Install the .NET SDK to run these examples.

    Reading & Writing Files

    The File class provides simple one-line methods for common operations. WriteAllText creates or overwrites, AppendAllText adds to the end, and ReadAllText loads everything into memory.

    Read & Write Text Files

    Write, read, and append to text files using the File class.

    Try it Yourself »
    C#
    using System;
    using System.IO;
    
    class Program
    {
        static void Main()
        {
            string filePath = "example.txt";
    
            // Write to a file (creates or overwrites)
            File.WriteAllText(filePath, "Hello from C#!\nThis is line 2.\nLine 3 here.");
            Console.WriteLine("✅ File written successfully");
    
            // Read entire file as string
            string content = File.ReadAllText(filePath);
            Console.WriteLine($"\n📄 File contents:\n{content}");
    
            // Read line by line
      
    ...

    StreamReader & StreamWriter

    For large files, use streams. They read/write data in chunks instead of loading everything at once. The using statement ensures the stream is properly closed even if an error occurs.

    Streaming Large Files

    Write 100 lines with StreamWriter and read the first 5 with StreamReader.

    Try it Yourself »
    C#
    using System;
    using System.IO;
    
    class Program
    {
        static void Main()
        {
            string filePath = "large-file.txt";
    
            // Create a sample file with many lines
            using (StreamWriter writer = new StreamWriter(filePath))
            {
                for (int i = 1; i <= 100; i++)
                    writer.WriteLine($"Data record #{i}: value={i * 3.14:F2}");
            }
            Console.WriteLine("✅ Created file with 100 lines");
    
            // StreamReader — read large files efficiently
            Co
    ...

    Directories & Paths

    The Directory class manages folders, and Path provides utilities for building file paths safely across different operating systems.

    Directories & Path Operations

    Create directories, list files, and build safe file paths.

    Try it Yourself »
    C#
    using System;
    using System.IO;
    
    class Program
    {
        static void Main()
        {
            // Check if directory exists
            string dir = "test-folder";
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
                Console.WriteLine($"📁 Created directory: {dir}");
            }
    
            // Create files in the directory
            File.WriteAllText(Path.Combine(dir, "notes.txt"), "My notes");
            File.WriteAllText(Path.Combine(dir, "data.csv"), "name,age\nAlice,
    ...

    Common Mistakes

    • Not using using: StreamReader/Writer must be disposed. Always wrap in using to prevent file locks.
    • Hardcoding paths: Use Path.Combine() instead of string concatenation — it handles OS-specific separators.
    • Not checking existence: Always use File.Exists() or Directory.Exists() before reading.

    JSON Serialization

    System.Text.Json (built into .NET) lets you convert objects to JSON strings and back. It's how modern C# apps read config files, communicate with APIs, and store structured data.

    JSON — Serialize & Deserialize

    Save and load a configuration object as a formatted JSON file.

    Try it Yourself »
    C#
    using System;
    using System.IO;
    using System.Text.Json;
    using System.Collections.Generic;
    
    class Config
    {
        public string AppName { get; set; }
        public int MaxRetries { get; set; }
        public List<string> AllowedHosts { get; set; }
        public bool DebugMode { get; set; }
    }
    
    class Program
    {
        static void Main()
        {
            // Create and serialize to JSON
            var config = new Config
            {
                AppName = "MyApp",
                MaxRetries = 3,
                AllowedHosts = new List
    ...

    Pro Tips

    • 💡 For files under 1 MB, File.ReadAllText is perfectly fine.
    • 💡 For files over 1 MB, switch to StreamReader to avoid memory issues.
    • 💡 Use async versions (ReadAllTextAsync) in web applications.
    • 💡 System.Text.Json is faster than Newtonsoft.Json for simple scenarios.

    Lesson Complete! 🎉

    You can now work with files and JSON in C#. Next: dive deeper into LINQ with advanced queries and optimization.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service