Let’s go through working with CSV and XML files in C# β€” common formats for data storage and exchange.


πŸ“Œ 1. Working with CSV Files

CSV (Comma-Separated Values) stores tabular data in plain text, where each line represents a record.


Reading CSV Files

using System;
using System.IO;
 
string path = "data.csv";
 
if (File.Exists(path))
{
    string[] lines = File.ReadAllLines(path);
    foreach (string line in lines)
    {
        string[] columns = line.Split(','); // Split by comma
        Console.WriteLine($"Name: {columns[0]}, Age: {columns[1]}");
    }
}
  • Simple and efficient for small CSV files

  • For large files, use StreamReader line by line


Writing CSV Files

using (StreamWriter writer = new StreamWriter("output.csv"))
{
    writer.WriteLine("Name,Age");
    writer.WriteLine("Alice,25");
    writer.WriteLine("Bob,30");
}
  • Always include headers for clarity

  • Use String.Join if writing arrays dynamically

string[] data = { "Charlie", "22" };
writer.WriteLine(string.Join(",", data));

πŸ“Œ 2. Working with XML Files

XML (eXtensible Markup Language) stores structured hierarchical data.


Creating XML with XDocument

using System.Xml.Linq;
 
XDocument doc = new XDocument(
    new XElement("People",
        new XElement("Person",
            new XElement("Name", "Alice"),
            new XElement("Age", 25)
        ),
        new XElement("Person",
            new XElement("Name", "Bob"),
            new XElement("Age", 30)
        )
    )
);
 
doc.Save("people.xml");
  • Creates a hierarchical XML structure

  • Saves to file using .Save()


Reading XML with XDocument

XDocument doc = XDocument.Load("people.xml");
foreach (XElement person in doc.Descendants("Person"))
{
    string name = person.Element("Name").Value;
    int age = int.Parse(person.Element("Age").Value);
    Console.WriteLine($"Name: {name}, Age: {age}");
}
  • Access elements and values with Element() and Descendants()

  • LINQ to XML makes queries concise and readable


πŸ“Œ 3. Advantages & Use Cases

FormatUse CaseAdvantages
CSVSimple tabular data, Excel export/importLightweight, easy to read/write
XMLHierarchical data, configuration files, SOAP APIsSupports nesting, schema validation, metadata

πŸ“Œ 4. Best Practices

  1. Use StreamReader / StreamWriter for large CSV files

  2. For complex CSVs, consider CSV libraries (e.g., CsvHelper)

  3. Use XDocument or XmlDocument for XML

  4. Validate XML with XSD schemas when necessary

  5. Always handle exceptions (FileNotFoundException, IOException)


βœ… Tip:

  • Use CSV for simple table-like data

  • Use XML for structured, hierarchical, or metadata-rich data