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()
andDescendants()
-
LINQ to XML makes queries concise and readable
π 3. Advantages & Use Cases
Format | Use Case | Advantages |
---|---|---|
CSV | Simple tabular data, Excel export/import | Lightweight, easy to read/write |
XML | Hierarchical data, configuration files, SOAP APIs | Supports nesting, schema validation, metadata |
π 4. Best Practices
-
Use
StreamReader
/StreamWriter
for large CSV files -
For complex CSVs, consider CSV libraries (e.g., CsvHelper)
-
Use
XDocument
orXmlDocument
for XML -
Validate XML with XSD schemas when necessary
-
Always handle exceptions (
FileNotFoundException
,IOException
)
β Tip:
-
Use CSV for simple table-like data
-
Use XML for structured, hierarchical, or metadata-rich data