FileIOSerializationScenarioQuestions

C# Question Bank

C# File IO & Serialization | 10 Scenario Questions (5 Moderate + 5 Complex) — Questions Only

Instruction: Students should implement ONLY the methods marked with // ✅ TODO.
Each question includes complex sample input (spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹, tricky file names). Replace it with your own as required.
Do not add answers in this page.
Moderate: 5 Complex: 5 Coverage: StreamWriter append, ReadAllLines parse, JSON serialize/deserialize, file filtering copy, atomic save, NDJSON streaming, CSV→JSON export, binary versioning header, GZip JSON
1

Write Cleaned Audit Lines — StreamWriter + Append

File IOStreamWriterAppendValidationModerate

Scenario: You receive audit lines (login/create) that include extra spaces and noisy symbols. You must clean them and append to a log file. What to implement: - AuditFile.AppendCleanLines(string filePath, List<string> lines) Rules: - Validate filePath not empty - For each line: trim; skip empty - Replace multiple spaces with single space - Append each cleaned line + newline to the file ✅ Implement ONLY the TODO method.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹, and tricky file names.
File IO + Serialization scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                         // Console
using System.Collections.Generic;                        // List
using System.IO;                                        // File IO
using System.Text.RegularExpressions;                   // Regex

namespace ItTechGenie.M1.FileIO.Q1
{
    public static class AuditFile
    {
        // ✅ TODO: Student must implement only this method
        public static void AppendCleanLines(string filePath, List<string> lines)
        {
            // TODO:
            // - validate inputs
            // - ensure directory exists
            // - open StreamWriter in append mode
            // - clean each line and write
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            var path = @".\data\audit log ✅.txt";
            var lines = new List<string>
            {
                "[2026-02-18 10:05]   USER='Sana @ Chennai'   ACTION='LOGIN'   IP='10.0.0.5' ",
                "   ",
                "[2026-02-18 10:06] USER='Ravi'   ACTION='CREATE'   SKU='SKU-β77'  "
            };

            AuditFile.AppendCleanLines(path, lines);
            Console.WriteLine("Done ✅");
        }
    }
}
2

Read CSV & Parse Records — File.ReadAllLines + Split

File IOReadAllLinesParsingCSVModerate

Scenario: A small CSV file contains product records with delimiter ';'. You must read the file and parse valid rows into objects. What to implement: - ProductCsv.Load(string filePath) Rules: - First line is header: "Sku;Name;Qty;Price" - Ignore invalid rows (wrong column count or qty not int or price not decimal) - Trim each field - Keep unicode SKU values ✅ Implement ONLY the TODO method.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹, and tricky file names.
File IO + Serialization scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                         // Console
using System.Collections.Generic;                        // List
using System.Globalization;                             // parsing
using System.IO;                                        // File IO
using System.Linq;                                      // LINQ

namespace ItTechGenie.M1.FileIO.Q2
{
    public record Product(string Sku, string Name, int Qty, decimal Price);

    public static class ProductCsv
    {
        // ✅ TODO: Student must implement only this method
        public static List<Product> Load(string filePath)
        {
            // TODO:
            // - validate path
            // - read all lines
            // - skip header
            // - split by ';'
            // - parse Qty and Price (remove ₹ and commas)
            // - ignore invalid rows
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            var path = @".\data\products;special ✅.csv";
            var products = ProductCsv.Load(path);

            foreach (var p in products)
                Console.WriteLine($"{p.Sku} | {p.Name} | {p.Qty} | ₹ {p.Price}");
        }
    }
}
3

Serialize Settings to JSON — System.Text.Json

SerializationJSONSystem.Text.JsonModerate

Scenario: Save app settings to a JSON file. The setting values may include spaces, quotes and unicode. What to implement: - SettingsStore.Save(string filePath, AppSettings settings) Rules: - Validate inputs - Ensure directory exists - Use System.Text.Json to serialize with indented output - Write UTF-8 text ✅ Implement ONLY the TODO method.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹, and tricky file names.
File IO + Serialization scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                         // Console
using System.IO;                                        // File IO
using System.Text.Json;                                 // JSON

namespace ItTechGenie.M1.Serialization.Q3
{
    public record AppSettings(string AppName, string AdminEmail, string BannerText);

    public static class SettingsStore
    {
        // ✅ TODO: Student must implement only this method
        public static void Save(string filePath, AppSettings settings)
        {
            // TODO:
            // - validate inputs
            // - create directory
            // - serialize with JsonSerializerOptions(WriteIndented=true)
            // - File.WriteAllText with UTF-8
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            var settings = new AppSettings("ItTechGenie - Practice", "admin+test@ittechgenie.com", "Welcome "Learner" ✅ α/β");
            SettingsStore.Save(@".\data\settings ✅.json", settings);
            Console.WriteLine("Saved ✅");
        }
    }
}
4

Deserialize JSON & Validate — Throw on Missing Fields

SerializationJSONValidationExceptionsModerate

Scenario: Load settings from JSON and validate mandatory fields. If AppName or AdminEmail is missing/empty -> throw FormatException. What to implement: - SettingsStore.Load(string filePath) Rules: - Read file - Deserialize JSON - Validate required fields - Return settings object ✅ Implement ONLY the TODO method.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹, and tricky file names.
File IO + Serialization scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                         // FormatException
using System.IO;                                        // File IO
using System.Text.Json;                                 // JSON

namespace ItTechGenie.M1.Serialization.Q4
{
    public record AppSettings(string AppName, string AdminEmail, string BannerText);

    public static class SettingsStore
    {
        // ✅ TODO: Student must implement only this method
        public static AppSettings Load(string filePath)
        {
            // TODO:
            // - validate path
            // - read text
            // - deserialize
            // - validate fields and throw FormatException if invalid
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            var s = SettingsStore.Load(@".\data\settings ✅.json");
            Console.WriteLine($"{s.AppName} | {s.AdminEmail} | {s.BannerText}");
        }
    }
}
5

Copy Files With Filtering — Directory.EnumerateFiles

File IODirectoryFilteringPathsModerate

Scenario: A backup tool must copy only specific files from a source folder to destination: - include extensions: .txt, .json - ignore files that contain the word "temp" (case-insensitive) What to implement: - BackupTool.CopySelected(string srcDir, string destDir) Rules: - Create destination directory if missing - Copy should overwrite existing files - Return count of copied files ✅ Implement ONLY the TODO method.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹, and tricky file names.
File IO + Serialization scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                         // Console
using System.IO;                                        // File IO
using System.Linq;                                      // LINQ

namespace ItTechGenie.M1.FileIO.Q5
{
    public static class BackupTool
    {
        // ✅ TODO: Student must implement only this method
        public static int CopySelected(string srcDir, string destDir)
        {
            // TODO:
            // - validate dirs
            // - create dest
            // - enumerate files
            // - filter by extension and not containing 'temp'
            // - copy with overwrite
            // - return count
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            var copied = BackupTool.CopySelected(@".\data\source files ✅", @".\data\backup 2026-02-18");
            Console.WriteLine($"Copied: {copied}");
        }
    }
}
6

Atomic Save — Write to Temp Then Replace

File IOAtomic ReplaceRobustnessComplex

Scenario: You must update a JSON file safely. If the application crashes mid-write, the file must not become partially written. What to implement: - AtomicWriter.SaveAtomic(string finalPath, string content) Rules: - Write to temp file in same directory (finalPath + ".tmp") - Flush and close writer - Replace original with temp (File.Replace or move strategy) - Cleanup temp on failure ✅ Implement ONLY the TODO method.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹, and tricky file names.
File IO + Serialization scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                         // Exception
using System.IO;                                        // File IO
using System.Text;                                      // Encoding

namespace ItTechGenie.M1.FileIO.Q6
{
    public static class AtomicWriter
    {
        // ✅ TODO: Student must implement only this method
        public static void SaveAtomic(string finalPath, string content)
        {
            // TODO:
            // - validate inputs
            // - ensure directory exists
            // - write temp file
            // - replace final file atomically
            // - cleanup temp on error
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            var path = @".\data\orders\order-O-90 01 ✅.json";
            var json = "{ \"orderId\": \"O-90 01\", \"amount\": \"₹ 1,999.25\", \"note\": \"paid ✅\" }";
            AtomicWriter.SaveAtomic(path, json);
            Console.WriteLine("Atomic save done ✅");
        }
    }
}
7

JSON Lines (NDJSON) — Stream Read + Yield Parse

File IOStreamingNDJSONSerializationComplex

Scenario: A log file is stored as NDJSON (one JSON object per line). You must stream the file and parse only valid lines. What to implement: - NdjsonReader.ReadValid(string filePath) Rules: - Use StreamReader to read line by line - Each line is JSON: {"id":"...", "level":"INFO", "msg":"..."} - Ignore invalid JSON lines - Return list of LogEvent ✅ Implement ONLY the TODO method.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹, and tricky file names.
File IO + Serialization scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                         // Console
using System.Collections.Generic;                        // List
using System.IO;                                        // StreamReader
using System.Text.Json;                                 // JSON

namespace ItTechGenie.M1.Serialization.Q7
{
    public record LogEvent(string Id, string Level, string Msg);

    public static class NdjsonReader
    {
        // ✅ TODO: Student must implement only this method
        public static List<LogEvent> ReadValid(string filePath)
        {
            // TODO:
            // - validate path
            // - stream read lines
            // - try deserialize each line
            // - ignore invalid JSON lines
            // - return list
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            var events = NdjsonReader.ReadValid(@".\data\ndjson\app-log ✅.ndjson");
            foreach (var e in events)
                Console.WriteLine($"{e.Level} | {e.Id} | {e.Msg}");
        }
    }
}
8

CSV to JSON Export — Serialize With Custom Property Names

File IOCSVJSON ExportMappingComplex

Scenario: A CSV file has columns: sku;name;qty;price You must convert it to a JSON array and save to output file. What to implement: - Exporter.CsvToJson(string csvPath, string jsonOutPath) Rules: - Parse price: remove ₹ and commas - Output JSON should use property names: sku, displayName, quantity, unitPrice - Write indented JSON - Ignore invalid rows but still export valid ones ✅ Implement ONLY the TODO method.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹, and tricky file names.
File IO + Serialization scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                         // Console
using System.Collections.Generic;                        // List
using System.Globalization;                             // parsing
using System.IO;                                        // File IO
using System.Text.Json;                                 // JSON

namespace ItTechGenie.M1.FileIO.Q8
{
    public record ExportRow(string sku, string displayName, int quantity, decimal unitPrice);

    public static class Exporter
    {
        // ✅ TODO: Student must implement only this method
        public static void CsvToJson(string csvPath, string jsonOutPath)
        {
            // TODO:
            // - validate paths
            // - read csv lines, skip header if present
            // - parse fields with delimiter ';'
            // - map to ExportRow
            // - serialize list to jsonOutPath (indented)
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            Exporter.CsvToJson(@".\data\export\in ✅.csv", @".\data\export\out ✅.json");
            Console.WriteLine("Exported ✅");
        }
    }
}
9

Versioned Binary Serialization — Save/Load With Header

SerializationBinaryVersioningStreamsComplex

Scenario: Store a small cache file in binary format with a header: - 4 bytes magic: 'ITQ1' - int version (1) - int recordCount Then for each record: - string key (length-prefixed) - decimal value (as string invariant) What to implement: - CacheBin.Save(string path, Dictionary<string, decimal> data) - CacheBin.Load(string path) -> Dictionary<string, decimal> Rules: - Keys may contain spaces/special chars/unicode - Validate magic and version on load; if invalid throw InvalidDataException ✅ Implement ONLY the TODO methods.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹, and tricky file names.
File IO + Serialization scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                         // Console
using System.Collections.Generic;                        // Dictionary
using System.Globalization;                             // InvariantCulture
using System.IO;                                        // Stream
using System.Text;                                      // Encoding

namespace ItTechGenie.M1.Serialization.Q9
{
    public static class CacheBin
    {
        private static readonly byte[] Magic = Encoding.ASCII.GetBytes("ITQ1"); // 4-byte magic

        // ✅ TODO: Student must implement only this method
        public static void Save(string path, Dictionary<string, decimal> data)
        {
            // TODO:
            // - validate inputs
            // - create directory
            // - write magic, version=1, count
            // - for each entry: write key length + key bytes; write decimal as invariant string length + bytes
            throw new NotImplementedException();
        }

        // ✅ TODO: Student must implement only this method
        public static Dictionary<string, decimal> Load(string path)
        {
            // TODO:
            // - validate path exists
            // - read and validate magic + version
            // - read count
            // - read each record and return dictionary
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            var data = new Dictionary<string, decimal>
            {
                ["SKU-α12"] = 1299.50m,
                ["User: Sana @ Chennai ✅"] = 1999.25m
            };

            var path = @".\data\cache\price cache ✅.bin";
            CacheBin.Save(path, data);

            var loaded = CacheBin.Load(path);

            foreach (var kv in loaded)
                Console.WriteLine($"{kv.Key} => ₹ {kv.Value}");
        }
    }
}
10

Compression + JSON — GZip Serialize/Deserialize

SerializationJSONGZipStreamsComplex

Scenario: You must store a list of orders as compressed JSON to reduce disk usage. File format: GZip-compressed UTF-8 JSON. What to implement: - OrderZip.SaveGz(string path, List<Order> orders) - OrderZip.LoadGz(string path) -> List<Order> Rules: - Use GZipStream - JSON must be indented when writing (even if compressed) - Orders can contain special chars/unicode - Validate file exists on load; throw FileNotFoundException if missing ✅ Implement ONLY the TODO methods.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹, and tricky file names.
File IO + Serialization scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                         // Console
using System.Collections.Generic;                        // List
using System.IO;                                        // File streams
using System.IO.Compression;                             // GZipStream
using System.Text;                                      // Encoding
using System.Text.Json;                                 // JSON

namespace ItTechGenie.M1.Serialization.Q10
{
    public record Order(string Id, string Customer, decimal Amount);

    public static class OrderZip
    {
        // ✅ TODO: Student must implement only this method
        public static void SaveGz(string path, List<Order> orders)
        {
            // TODO:
            // - validate inputs
            // - create directory
            // - create FileStream
            // - wrap with GZipStream (Compress)
            // - serialize JSON into stream (WriteIndented)
            throw new NotImplementedException();
        }

        // ✅ TODO: Student must implement only this method
        public static List<Order> LoadGz(string path)
        {
            // TODO:
            // - validate file exists
            // - open FileStream
            // - wrap with GZipStream (Decompress)
            // - deserialize JSON from stream
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            var orders = new List<Order>
            {
                new Order("O-90 01", "Sana @ Chennai ✅", 1999.25m),
                new Order("O-β77", "Ravi#QA", 7999m)
            };

            var path = @".\data\gz\orders ✅.json.gz";
            OrderZip.SaveGz(path, orders);

            var loaded = OrderZip.LoadGz(path);

            foreach (var o in loaded)
                Console.WriteLine($"{o.Id} | {o.Customer} | ₹ {o.Amount}");
        }
    }
}