C# & ASP.NET Topic

C# File I/O & Serialization

1. File System Operations

Basic File Operations

csharp

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;

public class BasicFileOperations
{
    public static void DemonstrateFileOperations()
    {
        string filePath = "sample.txt";
        string directoryPath = "TestData";
        
        // 1. Check if file exists
        if (File.Exists(filePath))
        {
            Console.WriteLine($"File {filePath} exists");
        }
        
        // 2. Create directory
        Directory.CreateDirectory(directoryPath);
        
        // 3. Write to file (overwrites if exists)
        File.WriteAllText(filePath, "Hello, World!\nThis is a test file.");
        
        // 4. Append to file
        File.AppendAllText(filePath, "\nAppended line.");
        
        // 5. Read all text
        string content = File.ReadAllText(filePath);
        Console.WriteLine("File content:");
        Console.WriteLine(content);
        
        // 6. Read all lines
        string[] lines = File.ReadAllLines(filePath);
        Console.WriteLine("\nFile lines:");
        foreach (string line in lines)
        {
            Console.WriteLine($"Line: {line}");
        }
        
        // 7. File information
        FileInfo fileInfo = new FileInfo(filePath);
        Console.WriteLine($"\nFile Info:");
        Console.WriteLine($"Name: {fileInfo.Name}");
        Console.WriteLine($"Size: {fileInfo.Length} bytes");
        Console.WriteLine($"Created: {fileInfo.CreationTime}");
        Console.WriteLine($"Last Modified: {fileInfo.LastWriteTime}");
        
        // 8. Copy file
        string copyPath = "sample_copy.txt";
        File.Copy(filePath, copyPath, overwrite: true);
        
        // 9. Move file
        string movedPath = Path.Combine(directoryPath, "sample_moved.txt");
        File.Move(copyPath, movedPath);
        
        // 10. Delete file
        File.Delete(movedPath);
    }
}

Working with Directories

csharp

public class DirectoryOperations
{
    public static void DemonstrateDirectoryOperations()
    {
        string basePath = "FileSystemDemo";
        
        // Clean up from previous runs
        if (Directory.Exists(basePath))
        {
            Directory.Delete(basePath, recursive: true);
        }
        
        // 1. Create directory structure
        Directory.CreateDirectory(basePath);
        Directory.CreateDirectory(Path.Combine(basePath, "SubFolder1"));
        Directory.CreateDirectory(Path.Combine(basePath, "SubFolder2"));
        Directory.CreateDirectory(Path.Combine(basePath, "SubFolder1", "DeepFolder"));
        
        // 2. Create some files
        File.WriteAllText(Path.Combine(basePath, "file1.txt"), "Content 1");
        File.WriteAllText(Path.Combine(basePath, "file2.txt"), "Content 2");
        File.WriteAllText(Path.Combine(basePath, "SubFolder1", "file3.txt"), "Content 3");
        File.WriteAllText(Path.Combine(basePath, "SubFolder2", "file4.txt"), "Content 4");
        
        // 3. List all files recursively
        Console.WriteLine("All files (recursive):");
        string[] allFiles = Directory.GetFiles(basePath, "*", SearchOption.AllDirectories);
        foreach (string file in allFiles)
        {
            Console.WriteLine($"  {file}");
        }
        
        // 4. List only .txt files in base directory
        Console.WriteLine("\n.txt files in base directory:");
        string[] txtFiles = Directory.GetFiles(basePath, "*.txt");
        foreach (string file in txtFiles)
        {
            Console.WriteLine($"  {Path.GetFileName(file)}");
        }
        
        // 5. List subdirectories
        Console.WriteLine("\nSubdirectories:");
        string[] subDirs = Directory.GetDirectories(basePath);
        foreach (string dir in subDirs)
        {
            Console.WriteLine($"  {Path.GetFileName(dir)}");
        }
        
        // 6. Get directory information
        DirectoryInfo dirInfo = new DirectoryInfo(basePath);
        Console.WriteLine($"\nDirectory Info:");
        Console.WriteLine($"Name: {dirInfo.Name}");
        Console.WriteLine($"Full Path: {dirInfo.FullName}");
        Console.WriteLine($"Created: {dirInfo.CreationTime}");
        Console.WriteLine($"Files Count: {dirInfo.GetFiles().Length}");
        Console.WriteLine($"Subdirectories Count: {dirInfo.GetDirectories().Length}");
        
        // 7. Check attributes
        Console.WriteLine($"Attributes: {dirInfo.Attributes}");
    }
}

Path Operations

csharp

public class PathOperations
{
    public static void DemonstratePathOperations()
    {
        string fullPath = @"C:\Users\JohnDoe\Documents\Projects\MyApp\src\program.cs";
        string relativePath = @"..\..\config\appsettings.json";
        
        Console.WriteLine("Path Operations:");
        Console.WriteLine($"Full Path: {fullPath}");
        Console.WriteLine($"Directory: {Path.GetDirectoryName(fullPath)}");
        Console.WriteLine($"File Name: {Path.GetFileName(fullPath)}");
        Console.WriteLine($"File Name Without Extension: {Path.GetFileNameWithoutExtension(fullPath)}");
        Console.WriteLine($"Extension: {Path.GetExtension(fullPath)}");
        Console.WriteLine($"Has Extension: {Path.HasExtension(fullPath)}");
        
        // Combine paths safely
        string baseDir = @"C:\MyApp";
        string configFile = "appsettings.json";
        string combined = Path.Combine(baseDir, "config", configFile);
        Console.WriteLine($"Combined Path: {combined}");
        
        // Get temporary paths
        Console.WriteLine($"Temp Path: {Path.GetTempPath()}");
        Console.WriteLine($"Random File Name: {Path.GetRandomFileName()}");
        Console.WriteLine($"Temp File: {Path.GetTempFileName()}");
        
        // Change extension
        string newPath = Path.ChangeExtension(fullPath, ".exe");
        Console.WriteLine($"Changed Extension: {newPath}");
        
        // Working with relative paths
        string currentDir = Directory.GetCurrentDirectory();
        string absolutePath = Path.GetFullPath(relativePath);
        Console.WriteLine($"Current Directory: {currentDir}");
        Console.WriteLine($"Relative Path: {relativePath}");
        Console.WriteLine($"Absolute Path: {absolutePath}");
    }
}

2. Streams - Low-Level File Operations

FileStream Basics

csharp

public class StreamOperations
{
    public static void DemonstrateFileStream()
    {
        string filePath = "stream_demo.dat";
        
        // Write using FileStream
        using (FileStream writeStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
        {
            string text = "Hello, FileStream World!";
            byte[] data = System.Text.Encoding.UTF8.GetBytes(text);
            
            writeStream.Write(data, 0, data.Length);
            Console.WriteLine($"Written {data.Length} bytes to file");
        }
        
        // Read using FileStream
        using (FileStream readStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            byte[] buffer = new byte[readStream.Length];
            int bytesRead = readStream.Read(buffer, 0, buffer.Length);
            
            string content = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine($"Read {bytesRead} bytes: {content}");
        }
        
        // Clean up
        File.Delete(filePath);
    }
    
    public static void DemonstrateStreamReaderWriter()
    {
        string filePath = "text_demo.txt";
        
        // Write using StreamWriter
        using (StreamWriter writer = new StreamWriter(filePath))
        {
            writer.WriteLine("Line 1: Hello StreamWriter!");
            writer.WriteLine("Line 2: This is easy to use.");
            writer.WriteLine("Line 3: Goodbye!");
        }
        
        // Read using StreamReader
        using (StreamReader reader = new StreamReader(filePath))
        {
            string line;
            int lineNumber = 1;
            
            Console.WriteLine("File content:");
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine($"{lineNumber}: {line}");
                lineNumber++;
            }
        }
        
        // Append using StreamWriter
        using (StreamWriter writer = new StreamWriter(filePath, append: true))
        {
            writer.WriteLine("Line 4: Appended line!");
        }
        
        Console.WriteLine("\nAfter append:");
        Console.WriteLine(File.ReadAllText(filePath));
        
        // Clean up
        File.Delete(filePath);
    }
}

Advanced Stream Operations

csharp

public class AdvancedStreamOperations
{
    public static void DemonstrateBinaryStreams()
    {
        string filePath = "binary_data.dat";
        
        // Write binary data
        using (BinaryWriter writer = new BinaryWriter(File.Create(filePath)))
        {
            writer.Write(42);                    // int
            writer.Write(3.14159);               // double
            writer.Write(true);                  // bool
            writer.Write("Hello Binary");        // string
            writer.Write(new byte[] { 0x01, 0x02, 0x03 }); // byte array
        }
        
        // Read binary data
        using (BinaryReader reader = new BinaryReader(File.OpenRead(filePath)))
        {
            int intValue = reader.ReadInt32();
            double doubleValue = reader.ReadDouble();
            bool boolValue = reader.ReadBoolean();
            string stringValue = reader.ReadString();
            byte[] byteArray = reader.ReadBytes(3);
            
            Console.WriteLine("Binary Data Read:");
            Console.WriteLine($"Int: {intValue}");
            Console.WriteLine($"Double: {doubleValue}");
            Console.WriteLine($"Bool: {boolValue}");
            Console.WriteLine($"String: {stringValue}");
            Console.WriteLine($"Bytes: {BitConverter.ToString(byteArray)}");
        }
        
        // Clean up
        File.Delete(filePath);
    }
    
    public static void DemonstrateMemoryStream()
    {
        // Create data in memory
        using (MemoryStream memoryStream = new MemoryStream())
        {
            // Write to memory stream
            using (StreamWriter writer = new StreamWriter(memoryStream, leaveOpen: true))
            {
                writer.WriteLine("Line 1 - In Memory");
                writer.WriteLine("Line 2 - Still in Memory");
                writer.Flush(); // Important: Ensure data is written to stream
                
                // Read from memory stream
                memoryStream.Position = 0; // Reset position to beginning
                
                using (StreamReader reader = new StreamReader(memoryStream))
                {
                    Console.WriteLine("Memory Stream Content:");
                    string content = reader.ReadToEnd();
                    Console.WriteLine(content);
                }
            }
        }
    }
    
    public static void DemonstrateBufferedStream()
    {
        string filePath = "buffered_demo.txt";
        
        using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
        using (BufferedStream bufferedStream = new BufferedStream(fileStream, 4096)) // 4KB buffer
        using (StreamWriter writer = new StreamWriter(bufferedStream))
        {
            for (int i = 0; i < 1000; i++)
            {
                writer.WriteLine($"Line {i}: This is buffered writing for better performance.");
            }
        }
        
        Console.WriteLine($"File created with {new FileInfo(filePath).Length} bytes");
        
        // Clean up
        File.Delete(filePath);
    }
}

3. JSON Serialization with System.Text.Json

Basic JSON Serialization

csharp

using System.Text.Json;
using System.Text.Json.Serialization;

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
    public DateTime DateOfBirth { get; set; }
    public List<string> Hobbies { get; set; } = new List<string>();
    public Address Address { get; set; }
    
    [JsonIgnore] // This property won't be serialized
    public string FullName => $"{FirstName} {LastName}";
}

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
    public string Country { get; set; } = "USA";
}

public class JsonSerializationDemo
{
    public static void DemonstrateBasicJsonSerialization()
    {
        var person = new Person
        {
            Id = 1,
            FirstName = "John",
            LastName = "Doe",
            Age = 30,
            Email = "john.doe@example.com",
            DateOfBirth = new DateTime(1993, 5, 15),
            Hobbies = new List<string> { "Reading", "Hiking", "Gaming" },
            Address = new Address
            {
                Street = "123 Main St",
                City = "New York",
                State = "NY",
                ZipCode = "10001"
            }
        };
        
        // Basic serialization
        string jsonString = JsonSerializer.Serialize(person);
        Console.WriteLine("Basic JSON Serialization:");
        Console.WriteLine(jsonString);
        
        // Pretty-printed serialization
        var options = new JsonSerializerOptions
        {
            WriteIndented = true,
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
        };
        
        string prettyJson = JsonSerializer.Serialize(person, options);
        Console.WriteLine("\nPretty JSON with Camel Case:");
        Console.WriteLine(prettyJson);
        
        // Deserialization
        Person deserializedPerson = JsonSerializer.Deserialize<Person>(prettyJson, options);
        Console.WriteLine($"\nDeserialized Person: {deserializedPerson.FirstName} {deserializedPerson.LastName}");
    }
}

Advanced JSON Serialization

csharp

public class AdvancedJsonSerialization
{
    public static void DemonstrateCustomJsonOptions()
    {
        var person = new Person
        {
            Id = 2,
            FirstName = "Jane",
            LastName = "Smith",
            Age = 25,
            Email = "jane.smith@example.com",
            DateOfBirth = new DateTime(1998, 8, 22),
            Hobbies = new List<string> { "Painting", "Yoga" },
            Address = new Address
            {
                Street = "456 Oak Ave",
                City = "Los Angeles",
                State = "CA",
                ZipCode = "90210"
            }
        };
        
        // Custom JSON serializer options
        var options = new JsonSerializerOptions
        {
            WriteIndented = true,
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
            Converters = { new JsonStringEnumConverter() }
        };
        
        string json = JsonSerializer.Serialize(person, options);
        Console.WriteLine("Custom JSON Serialization:");
        Console.WriteLine(json);
        
        // Serialize to file
        string filePath = "person.json";
        File.WriteAllText(filePath, json);
        Console.WriteLine($"\nJSON written to {filePath}");
        
        // Deserialize from file
        string jsonFromFile = File.ReadAllText(filePath);
        Person personFromFile = JsonSerializer.Deserialize<Person>(jsonFromFile, options);
        Console.WriteLine($"\nPerson from file: {personFromFile.FirstName} {personFromFile.LastName}");
        
        // Clean up
        File.Delete(filePath);
    }
    
    public static void DemonstrateCollectionsSerialization()
    {
        var people = new List<Person>
        {
            new Person { Id = 1, FirstName = "Alice", LastName = "Johnson", Age = 28 },
            new Person { Id = 2, FirstName = "Bob", LastName = "Williams", Age = 32 },
            new Person { Id = 3, FirstName = "Charlie", LastName = "Brown", Age = 24 }
        };
        
        var options = new JsonSerializerOptions { WriteIndented = true };
        
        string json = JsonSerializer.Serialize(people, options);
        Console.WriteLine("JSON Array Serialization:");
        Console.WriteLine(json);
        
        // Deserialize collection
        List<Person> deserializedPeople = JsonSerializer.Deserialize<List<Person>>(json, options);
        Console.WriteLine($"\nDeserialized {deserializedPeople.Count} people");
    }
}

JSON with Custom Converters

csharp

// Custom JSON converter for specific formatting
public class CustomDateTimeConverter : JsonConverter<DateTime>
{
    private readonly string _format;
    
    public CustomDateTimeConverter(string format = "yyyy-MM-dd")
    {
        _format = format;
    }
    
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return DateTime.ParseExact(reader.GetString(), _format, null);
    }
    
    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString(_format));
    }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    
    [JsonConverter(typeof(CustomDateTimeConverter))]
    public DateTime ManufactureDate { get; set; }
    
    [JsonConverter(typeof(CustomDateTimeConverter))]
    public DateTime? ExpiryDate { get; set; } // Nullable datetime
    
    [JsonNumberHandling(JsonNumberHandling.AllowNamedFloatingPointLiterals)]
    public decimal Discount { get; set; }
}

public class CustomJsonSerialization
{
    public static void DemonstrateCustomConverters()
    {
        var product = new Product
        {
            Id = 1,
            Name = "Laptop",
            Price = 999.99m,
            ManufactureDate = new DateTime(2023, 1, 15),
            ExpiryDate = null,
            Discount = 0.1m
        };
        
        var options = new JsonSerializerOptions
        {
            WriteIndented = true,
            Converters = { new CustomDateTimeConverter() }
        };
        
        string json = JsonSerializer.Serialize(product, options);
        Console.WriteLine("JSON with Custom Converters:");
        Console.WriteLine(json);
        
        // Round-trip: serialize and deserialize
        Product deserializedProduct = JsonSerializer.Deserialize<Product>(json, options);
        Console.WriteLine($"\nDeserialized Product: {deserializedProduct.Name}");
    }
}

4. XML Serialization

Basic XML Serialization

csharp

using System.Xml.Serialization;
using System.Text;

public class XmlSerializationDemo
{
    public static void DemonstrateBasicXmlSerialization()
    {
        var person = new Person
        {
            Id = 1,
            FirstName = "John",
            LastName = "Doe",
            Age = 30,
            Email = "john.doe@example.com",
            DateOfBirth = new DateTime(1993, 5, 15),
            Hobbies = new List<string> { "Reading", "Hiking" },
            Address = new Address
            {
                Street = "123 Main St",
                City = "New York",
                State = "NY",
                ZipCode = "10001"
            }
        };
        
        // XML Serialization
        XmlSerializer serializer = new XmlSerializer(typeof(Person));
        
        using (StringWriter writer = new StringWriter())
        {
            serializer.Serialize(writer, person);
            string xmlString = writer.ToString();
            Console.WriteLine("XML Serialization:");
            Console.WriteLine(xmlString);
            
            // Save to file
            string filePath = "person.xml";
            File.WriteAllText(filePath, xmlString);
            Console.WriteLine($"\nXML written to {filePath}");
            
            // Deserialize from file
            string xmlFromFile = File.ReadAllText(filePath);
            using (StringReader reader = new StringReader(xmlFromFile))
            {
                Person deserializedPerson = (Person)serializer.Deserialize(reader);
                Console.WriteLine($"\nDeserialized Person: {deserializedPerson.FirstName} {deserializedPerson.LastName}");
            }
            
            // Clean up
            File.Delete(filePath);
        }
    }
    
    public static void DemonstrateXmlWithAttributes()
    {
        // Class with XML attributes for control
        [XmlRoot("Employee")]
        public class Employee
        {
            [XmlAttribute("id")]
            public int Id { get; set; }
            
            [XmlElement("FirstName")]
            public string FirstName { get; set; }
            
            [XmlElement("LastName")]
            public string LastName { get; set; }
            
            [XmlIgnore]
            public string Password { get; set; }
            
            [XmlArray("Skills")]
            [XmlArrayItem("Skill")]
            public List<string> Skills { get; set; } = new List<string>();
            
            [XmlElement("HireDate", DataType = "date")]
            public DateTime HireDate { get; set; }
        }
        
        var employee = new Employee
        {
            Id = 101,
            FirstName = "Alice",
            LastName = "Johnson",
            Password = "secret123",
            Skills = new List<string> { "C#", "SQL", "JavaScript" },
            HireDate = new DateTime(2020, 3, 15)
        };
        
        XmlSerializer serializer = new XmlSerializer(typeof(Employee));
        
        using (StringWriter writer = new StringWriter())
        {
            serializer.Serialize(writer, employee);
            Console.WriteLine("XML with Attributes:");
            Console.WriteLine(writer.ToString());
        }
    }
}

Advanced XML Operations

csharp

public class AdvancedXmlOperations
{
    public static void DemonstrateXmlCollections()
    {
        [XmlRoot("Company")]
        public class Company
        {
            [XmlElement("Name")]
            public string Name { get; set; }
            
            [XmlArray("Employees")]
            [XmlArrayItem("Employee")]
            public List<Employee> Employees { get; set; } = new List<Employee>();
            
            [XmlArray("Departments")]
            [XmlArrayItem("Department")]
            public List<Department> Departments { get; set; } = new List<Department>();
        }
        
        public class Employee
        {
            [XmlAttribute("id")]
            public int Id { get; set; }
            
            [XmlElement("Name")]
            public string Name { get; set; }
            
            [XmlElement("Position")]
            public string Position { get; set; }
        }
        
        public class Department
        {
            [XmlAttribute("code")]
            public string Code { get; set; }
            
            [XmlElement("Name")]
            public string Name { get; set; }
            
            [XmlElement("Manager")]
            public string Manager { get; set; }
        }
        
        var company = new Company
        {
            Name = "Tech Solutions Inc.",
            Employees = new List<Employee>
            {
                new Employee { Id = 1, Name = "John Doe", Position = "Developer" },
                new Employee { Id = 2, Name = "Jane Smith", Position = "Designer" },
                new Employee { Id = 3, Name = "Bob Johnson", Position = "Manager" }
            },
            Departments = new List<Department>
            {
                new Department { Code = "DEV", Name = "Development", Manager = "Bob Johnson" },
                new Department { Code = "DES", Name = "Design", Manager = "Jane Smith" }
            }
        };
        
        XmlSerializer serializer = new XmlSerializer(typeof(Company));
        
        using (StringWriter writer = new StringWriter())
        {
            serializer.Serialize(writer, company);
            Console.WriteLine("Complex XML with Collections:");
            Console.WriteLine(writer.ToString());
            
            // Save to file
            string filePath = "company.xml";
            File.WriteAllText(filePath, writer.ToString());
            
            // Read and deserialize
            string xmlContent = File.ReadAllText(filePath);
            using (StringReader reader = new StringReader(xmlContent))
            {
                Company deserializedCompany = (Company)serializer.Deserialize(reader);
                Console.WriteLine($"\nDeserialized Company: {deserializedCompany.Name}");
                Console.WriteLine($"Employees: {deserializedCompany.Employees.Count}");
                Console.WriteLine($"Departments: {deserializedCompany.Departments.Count}");
            }
            
            // Clean up
            File.Delete(filePath);
        }
    }
}

5. Real-World File Operations

Configuration File Management

csharp

public class AppSettings
{
    public string AppName { get; set; } = "MyApplication";
    public string Version { get; set; } = "1.0.0";
    public DatabaseSettings Database { get; set; } = new DatabaseSettings();
    public LoggingSettings Logging { get; set; } = new LoggingSettings();
    public List<string> Features { get; set; } = new List<string>();
}

public class DatabaseSettings
{
    public string ConnectionString { get; set; } = "Server=localhost;Database=MyApp;Trusted_Connection=true;";
    public int Timeout { get; set; } = 30;
    public bool EnableLogging { get; set; } = true;
}

public class LoggingSettings
{
    public string Level { get; set; } = "Information";
    public string FilePath { get; set; } = "logs/app.log";
    public int MaxFileSizeMB { get; set; } = 10;
    public bool EnableConsole { get; set; } = true;
}

public class ConfigurationManager
{
    private readonly string _configFilePath;
    
    public ConfigurationManager(string configFilePath = "appsettings.json")
    {
        _configFilePath = configFilePath;
    }
    
    public AppSettings LoadSettings()
    {
        if (!File.Exists(_configFilePath))
        {
            // Create default settings if file doesn't exist
            var defaultSettings = new AppSettings();
            SaveSettings(defaultSettings);
            return defaultSettings;
        }
        
        string json = File.ReadAllText(_configFilePath);
        var options = new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
        
        return JsonSerializer.Deserialize<AppSettings>(json, options);
    }
    
    public void SaveSettings(AppSettings settings)
    {
        var options = new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
        string json = JsonSerializer.Serialize(settings, options);
        
        // Ensure directory exists
        string directory = Path.GetDirectoryName(_configFilePath);
        if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
        {
            Directory.CreateDirectory(directory);
        }
        
        File.WriteAllText(_configFilePath, json);
    }
    
    public void UpdateSetting<T>(string propertyPath, T value)
    {
        var settings = LoadSettings();
        
        // Simple property path resolution (for demo - in real app, use more robust approach)
        var properties = propertyPath.Split('.');
        object currentObj = settings;
        
        for (int i = 0; i < properties.Length - 1; i++)
        {
            var property = currentObj.GetType().GetProperty(properties[i]);
            currentObj = property.GetValue(currentObj);
        }
        
        var finalProperty = currentObj.GetType().GetProperty(properties[^1]);
        finalProperty.SetValue(currentObj, value);
        
        SaveSettings(settings);
    }
}

public class ConfigurationDemo
{
    public static void DemonstrateConfigurationManagement()
    {
        var configManager = new ConfigurationManager("config/appsettings.json");
        
        // Load or create settings
        var settings = configManager.LoadSettings();
        Console.WriteLine($"Loaded settings for: {settings.AppName} v{settings.Version}");
        
        // Modify settings
        settings.Version = "1.1.0";
        settings.Features.Add("NewDashboard");
        settings.Features.Add("AdvancedReporting");
        settings.Database.Timeout = 60;
        
        // Save updated settings
        configManager.SaveSettings(settings);
        Console.WriteLine("Settings updated and saved");
        
        // Update specific setting
        configManager.UpdateSetting("Logging.Level", "Debug");
        configManager.UpdateSetting("Database.EnableLogging", false);
        
        // Verify changes
        var updatedSettings = configManager.LoadSettings();
        Console.WriteLine($"Log Level: {updatedSettings.Logging.Level}");
        Console.WriteLine($"Database Logging: {updatedSettings.Database.EnableLogging}");
        Console.WriteLine($"Features: {string.Join(", ", updatedSettings.Features)}");
    }
}

Data Export Service

csharp

public class DataExportService
{
    public void ExportToJson<T>(IEnumerable<T> data, string filePath)
    {
        var options = new JsonSerializerOptions
        {
            WriteIndented = true,
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
        };
        
        string json = JsonSerializer.Serialize(data, options);
        File.WriteAllText(filePath, json);
        Console.WriteLine($"Exported {data.Count()} items to {filePath}");
    }
    
    public void ExportToXml<T>(IEnumerable<T> data, string filePath)
    {
        var serializer = new XmlSerializer(typeof(List<T>));
        
        using (var writer = new StreamWriter(filePath))
        {
            serializer.Serialize(writer, data.ToList());
        }
        
        Console.WriteLine($"Exported {data.Count()} items to {filePath}");
    }
    
    public void ExportToCsv<T>(IEnumerable<T> data, string filePath)
    {
        var properties = typeof(T).GetProperties();
        
        using (var writer = new StreamWriter(filePath))
        {
            // Write header
            var header = string.Join(",", properties.Select(p => p.Name));
            writer.WriteLine(header);
            
            // Write data
            foreach (var item in data)
            {
                var values = properties.Select(p => 
                {
                    var value = p.GetValue(item);
                    return value != null ? $"\"{value.ToString().Replace("\"", "\"\"")}\"" : "\"\"";
                });
                
                writer.WriteLine(string.Join(",", values));
            }
        }
        
        Console.WriteLine($"Exported {data.Count()} items to {filePath}");
    }
    
    public async Task ExportLargeDataAsync<T>(IEnumerable<T> data, string filePath, int batchSize = 1000)
    {
        var options = new JsonSerializerOptions { WriteIndented = true };
        
        using (var fileStream = new FileStream(filePath, FileMode.Create))
        await using (var writer = new Utf8JsonWriter(fileStream))
        {
            writer.WriteStartArray();
            
            int count = 0;
            foreach (var item in data)
            {
                JsonSerializer.Serialize(writer, item, options);
                count++;
                
                if (count % batchSize == 0)
                {
                    await writer.FlushAsync();
                    Console.WriteLine($"Processed {count} items...");
                }
            }
            
            writer.WriteEndArray();
        }
        
        Console.WriteLine($"Completed export of {data.Count()} items to {filePath}");
    }
}

public class DataExportDemo
{
    public static void DemonstrateDataExport()
    {
        var products = new List<Product>
        {
            new Product { Id = 1, Name = "Laptop", Price = 999.99m, ManufactureDate = DateTime.Now.AddDays(-100) },
            new Product { Id = 2, Name = "Mouse", Price = 29.99m, ManufactureDate = DateTime.Now.AddDays(-50) },
            new Product { Id = 3, Name = "Keyboard", Price = 79.99m, ManufactureDate = DateTime.Now.AddDays(-30) }
        };
        
        var exportService = new DataExportService();
        
        // Export to different formats
        exportService.ExportToJson(products, "products.json");
        exportService.ExportToXml(products, "products.xml");
        exportService.ExportToCsv(products, "products.csv");
        
        // Clean up
        File.Delete("products.json");
        File.Delete("products.xml");
        File.Delete("products.csv");
    }
}

Key Concepts Summary

  1. File I/O: Use File, Directory, Path classes for basic operations

  2. Streams: FileStream, StreamReader/Writer, BinaryReader/Writer for low-level control

  3. JSON Serialization: System.Text.Json for modern, high-performance JSON handling

  4. XML Serialization: XmlSerializer for XML data interchange

  5. Best Practices:

    • Always use using statements for resource management

    • Handle exceptions appropriately

    • Consider performance for large files (use streaming)

    • Validate file paths and check for existence

    • Use async operations for better scalability

These file I/O and serialization techniques are essential for building applications that need to persist data, communicate with other systems, or manage configuration.

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?