CSV File Handling - potatoscript/csharp GitHub Wiki
A CSV (Comma-Separated Values) file is a simple text format used to store data in a table-like structure. Each line in the file represents a row of data, and the values in that row are separated by commas ,
.
π Think of a CSV file as a spreadsheet π, but instead of cells, itβs all in plain text!
π You can open CSV files with programs like Excel, Google Sheets, or even a text editor.
Name,Age,Favorite Food
PotatoScript,10,French Fries
Lucy Berry,25,Mashed Potatoes
Snoopy,5,Potato Chips
β
Easy to read and write β Simple format that any text editor can open.
β
Cross-platform β Can be used across different operating systems.
β
Compatible β Can be easily imported into databases or spreadsheets.
Imagine that PotatoScript wants to save her favorite potato recipes π₯ in a CSV file and read them later to decide what to cook! π²β¨
There are two main ways to handle CSV files in C#:
π Method | π Purpose |
---|---|
StreamReader |
Read data from a CSV file. |
StreamWriter |
Write data to a CSV file. |
String.Join() |
Convert array or list data to CSV. |
String.Split() |
Parse CSV lines into arrays. |
To write data to a CSV file, weβll use StreamWriter
.
using System;
using System.IO;
class Program
{
static void Main()
{
string csvFile = "potato_recipes.csv";
// Create a StreamWriter to write to the file
using (StreamWriter writer = new StreamWriter(csvFile))
{
// Write header row
writer.WriteLine("Name,Type,Rating");
// Write some potato recipes
writer.WriteLine("French Fries,Snack,5");
writer.WriteLine("Mashed Potatoes,Side Dish,4.5");
writer.WriteLine("Potato Chips,Snack,4.8");
Console.WriteLine("CSV file created successfully! ππ₯");
}
}
}
CSV file created successfully! ππ₯
Name,Type,Rating
French Fries,Snack,5
Mashed Potatoes,Side Dish,4.5
Potato Chips,Snack,4.8
β Explanation:
-
StreamWriter
writes text data topotato_recipes.csv
. -
writer.WriteLine()
adds each line to the file. - The header row describes the columns:
Name
,Type
, andRating
.
To read data from a CSV file, weβll use StreamReader
.
using System;
using System.IO;
class Program
{
static void Main()
{
string csvFile = "potato_recipes.csv";
// Create a StreamReader to read the file
using (StreamReader reader = new StreamReader(csvFile))
{
string line;
// Read header row first
if ((line = reader.ReadLine()) != null)
{
Console.WriteLine("π Header: " + line);
}
// Read the rest of the rows
while ((line = reader.ReadLine()) != null)
{
string[] data = line.Split(',');
Console.WriteLine($"π₯ Name: {data[0]}, Type: {data[1]}, Rating: {data[2]}");
}
}
}
}
π Header: Name,Type,Rating
π₯ Name: French Fries, Type: Snack, Rating: 5
π₯ Name: Mashed Potatoes, Type: Side Dish, Rating: 4.5
π₯ Name: Potato Chips, Type: Snack, Rating: 4.8
β Explanation:
-
StreamReader
reads the CSV file line by line. -
line.Split(',')
splits each row into individual columns. - We print the data row by row in a friendly format. π₯
If you want to add more data without deleting existing content, use StreamWriter
with append mode.
using System;
using System.IO;
class Program
{
static void Main()
{
string csvFile = "potato_recipes.csv";
// Open the file in append mode
using (StreamWriter writer = new StreamWriter(csvFile, true))
{
// Add new recipes
writer.WriteLine("Potato Casserole,Main Dish,4.9");
writer.WriteLine("Potato Soup,Soup,4.7");
Console.WriteLine("New recipes added to the file! π²π");
}
}
}
New recipes added to the file! π²π
Name,Type,Rating
French Fries,Snack,5
Mashed Potatoes,Side Dish,4.5
Potato Chips,Snack,4.8
Potato Casserole,Main Dish,4.9
Potato Soup,Soup,4.7
If you have CSV data stored as a string in memory, you can parse it easily using String.Split()
.
using System;
class Program
{
static void Main()
{
string csvData = "Name,Type,Rating\nFrench Fries,Snack,5\nMashed Potatoes,Side Dish,4.5";
string[] rows = csvData.Split('\n');
foreach (string row in rows)
{
string[] columns = row.Split(',');
// Skip header row
if (columns[0] != "Name")
{
Console.WriteLine($"π₯ Name: {columns[0]}, Type: {columns[1]}, Rating: {columns[2]}");
}
}
}
}
π₯ Name: French Fries, Type: Snack, Rating: 5
π₯ Name: Mashed Potatoes, Type: Side Dish, Rating: 4.5
β Explanation:
-
csvData.Split('\n')
splits the CSV data into rows. -
row.Split(',')
splits each row into columns. - The header row is ignored to avoid printing it.
If you have data in an array or list, you can use String.Join()
to create a CSV row.
using System;
class Program
{
static void Main()
{
string[] potatoData = { "Baked Potatoes", "Side Dish", "4.7" };
// Join array elements with commas to create a CSV row
string csvRow = String.Join(",", potatoData);
Console.WriteLine("π₯ CSV Row: " + csvRow);
}
}
π₯ CSV Row: Baked Potatoes,Side Dish,4.7
For advanced scenarios, you can read CSV data directly into a List or Dictionary.
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static void Main()
{
string csvFile = "potato_recipes.csv";
List<string[]> recipes = new List<string[]>();
using (StreamReader reader = new StreamReader(csvFile))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] data = line.Split(',');
recipes.Add(data);
}
}
// Print the recipes
foreach (var row in recipes)
{
Console.WriteLine($"π₯ Name: {row[0]}, Type: {row[1]}, Rating: {row[2]}");
}
}
}