CSV File Handling - potatoscript/csharp GitHub Wiki

πŸ“š CSV File Handling in C# πŸ“š


πŸ₯” What is a CSV File?

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.


πŸ“„ Example of a CSV File:

Name,Age,Favorite Food
PotatoScript,10,French Fries
Lucy Berry,25,Mashed Potatoes
Snoopy,5,Potato Chips

🎯 Why Use CSV Files?

βœ… 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! 🍲✨


πŸ“„ How to Handle CSV Files in C#

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.

πŸ“ Step 1: Writing Data to a CSV File

To write data to a CSV file, we’ll use StreamWriter.


✏️ Basic Syntax:

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! πŸ“„πŸ₯”");
        }
    }
}

🎁 Output:

CSV file created successfully! πŸ“„πŸ₯”

πŸ“„ potato_recipes.csv Content:

Name,Type,Rating
French Fries,Snack,5
Mashed Potatoes,Side Dish,4.5
Potato Chips,Snack,4.8

βœ… Explanation:

  • StreamWriter writes text data to potato_recipes.csv.
  • writer.WriteLine() adds each line to the file.
  • The header row describes the columns: Name, Type, and Rating.

πŸ“ Step 2: Reading Data from a CSV File

To read data from a CSV file, we’ll use StreamReader.


πŸ“„ Reading the CSV File:

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]}");
            }
        }
    }
}

🎁 Output:

πŸ“ 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. πŸ₯”

πŸ“ Step 3: Appending Data to an Existing CSV File

If you want to add more data without deleting existing content, use StreamWriter with append mode.


✏️ Appending to CSV File:

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! πŸ²πŸ“„");
        }
    }
}

🎁 Output:

New recipes added to the file! πŸ²πŸ“„

πŸ“„ Updated potato_recipes.csv:

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

πŸ“ Step 4: Parsing CSV Data with String.Split()

If you have CSV data stored as a string in memory, you can parse it easily using String.Split().


🧠 Example:

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]}");
            }
        }
    }
}

🎁 Output:

πŸ₯” 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.

πŸ“ Step 5: Using String.Join() to Create CSV Data

If you have data in an array or list, you can use String.Join() to create a CSV row.


🧠 Example:

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);
    }
}

🎁 Output:

πŸ₯” CSV Row: Baked Potatoes,Side Dish,4.7

πŸ“ Step 6: Reading CSV into List or Dictionary

For advanced scenarios, you can read CSV data directly into a List or Dictionary.


πŸ“š Reading CSV into a List:

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]}");
        }
    }
}
⚠️ **GitHub.com Fallback** ⚠️