Working with Data in C#

by mahidhar

Handling data efficiently is a critical part of software development. This section covers various techniques for working with data in C#, including File I/O, serialization, and database operations with Entity Framework.

File I/O
File I/O operations allow you to read from and write to files on the filesystem. C# provides several classes in the System.IO namespace for these operations.

Reading from a File:

Use StreamReader for reading text files.
File.ReadAllText and File.ReadAllLines are simpler alternatives for small files.
Example:

code
using System;
using System.IO;

namespace NationalParks
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = "parks.txt";

            // Simple method to read all text
            string content = File.ReadAllText(path);
            Console.WriteLine("File content:\n" + content);

            // Using StreamReader
            using (StreamReader reader = new StreamReader(path))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
    }
}

Writing to a File:

Use StreamWriter for writing text files.
File.WriteAllText and File.WriteAllLines are simpler alternatives for small files.
Example:

code
using System;
using System.IO;

namespace NationalParks
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = "parks.txt";
            string[] parks = { "Yellowstone", "Yosemite", "Zion", "Grand Canyon" };

            // Simple method to write all text
            File.WriteAllText(path, "Yellowstone\nYosemite\nZion\nGrand Canyon");

            // Using StreamWriter
            using (StreamWriter writer = new StreamWriter(path))
            {
                foreach (string park in parks)
                {
                    writer.WriteLine(park);
                }
            }

            Console.WriteLine("File written successfully.");
        }
    }
}

Serialization
Serialization is the process of converting an object into a format that can be stored or transmitted and then reconstructing it later.

JSON Serialization:

Use JsonSerializer from System.Text.Json.
Example:

code
using System;
using System.Text.Json;
using System.IO;

namespace NationalParks
{
    public class Park
    {
        public string Name { get; set; }
        public int YearEstablished { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Park park = new Park { Name = "Yellowstone", YearEstablished = 1872 };

            // Serialize to JSON
            string json = JsonSerializer.Serialize(park);
            File.WriteAllText("park.json", json);
            Console.WriteLine("JSON written: " + json);

            // Deserialize from JSON
            string jsonData = File.ReadAllText("park.json");
            Park deserializedPark = JsonSerializer.Deserialize<Park>(jsonData);
            Console.WriteLine($"Park: {deserializedPark.Name}, Established: {deserializedPark.YearEstablished}");
        }
    }
}

XML Serialization:

Use XmlSerializer from System.Xml.Serialization.
Example:

code
using System;
using System.IO;
using System.Xml.Serialization;

namespace NationalParks
{
    public class Park
    {
        public string Name { get; set; }
        public int YearEstablished { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Park park = new Park { Name = "Yellowstone", YearEstablished = 1872 };

            // Serialize to XML
            XmlSerializer serializer = new XmlSerializer(typeof(Park));
            using (FileStream stream = new FileStream("park.xml", FileMode.Create))
            {
                serializer.Serialize(stream, park);
            }
            Console.WriteLine("XML written.");

            // Deserialize from XML
            using (FileStream stream = new FileStream("park.xml", FileMode.Open))
            {
                Park deserializedPark = (Park)serializer.Deserialize(stream);
                Console.WriteLine($"Park: {deserializedPark.Name}, Established: {deserializedPark.YearEstablished}");
            }
        }
    }
}