Skip to main content

.NET C#/VB
Read & Write CSV Files with Ease



C#

// AZUL CODING ---------------------------------------
// .NET C#/VB - Read & Write CSV Files with Ease
// https://youtu.be/9PWX89Sooac


using System.Globalization;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using Microsoft.Win32;
using CsvHelper;
using CsvHelper.Configuration.Attributes;
using CsvHelper.Configuration;

namespace CSVFiles
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private static readonly OpenFileDialog OpenDialog = new()
        {
            Title = "Select a CSV file",
            Filter = "CSV files (.csv)|*.csv"
        };

        private static readonly SaveFileDialog SaveDialog = new()
        {
            Title = "Save to a CSV file",
            Filter = "CSV files (.csv)|*.csv"
        };

        public MainWindow()
        {
            InitializeComponent();
        }

        private void ReadBtn_Click(object sender, RoutedEventArgs e)
        {
            if (OpenDialog.ShowDialog() == true)
            {
                using StreamReader reader = new(OpenDialog.FileName);
                using CsvReader csv = new(reader, CultureInfo.InvariantCulture);

                DataTable.ItemsSource = csv.GetRecords<Person>();

                // If you don't want to use a custom class, try this...
                // csv.GetRecords<dynamic>();
            }
        }

        private void WriteBtn_Click(object sender, RoutedEventArgs e)
        {
            List<Person> persons = new()
            {
                new Person() {
                    ID = 1,
                    Name = "John Doe",
                    Email = "johndoe@example.com",
                    PhoneNumber = "123-456-7890",
                    IsEmployed = true
                },
                new Person() {
                    ID = 2,
                    Name = "Jane Smith",
                    Email = "janesmith@example.com",
                    PhoneNumber = "098-765-4321",
                    IsEmployed = false
                }
            };

            if (SaveDialog.ShowDialog() == true)
            {
                using StreamWriter writer = new(SaveDialog.FileName);
                using CsvWriter csv = new(writer, CultureInfo.InvariantCulture);

                csv.WriteRecords(persons);
            }
        }

        private void EditBtn_Click(object sender, RoutedEventArgs e)
        {
            List<Person> newPersons = new()
            {
                new Person() {
                    ID = 4,
                    Name = "Emma John",
                    Email = "emma@example.com",
                    PhoneNumber = "987-654-3210",
                    IsEmployed = false
                }
            };

            if (OpenDialog.ShowDialog() == true)
            {
                CsvConfiguration config = new(CultureInfo.InvariantCulture)
                {
                    HasHeaderRecord = false
                };

                using FileStream stream = File.Open(OpenDialog.FileName, FileMode.Append);
                using StreamWriter writer = new(stream);
                using CsvWriter csv = new(writer, config);

                csv.WriteRecords(newPersons);
            }
        }
    }
    
    public class Person
    {
        public int ID { get; set; }
        public string Name { get; set; } = "";
        public string Email { get; set; } = "";
        public string PhoneNumber { get; set; } = "";
        public bool IsEmployed { get; set; }
    }

    public class Person2
    {
        public int ID { get; set; }

        [Name("Full Name")]
        public string Name { get; set; } = "";

        [Ignore]
        public string Email { get; set; } = "sample@example.com";

        [Index(2)]
        public string PhoneNumber { get; set; } = "";

        [Name("Employed?")]
        [BooleanTrueValues("yes")]
        [BooleanFalseValues("no")]
        public bool IsEmployed { get; set; }
    }
}

Enjoying this tutorial?


VB.NET

' AZUL CODING ---------------------------------------
' .NET C#/VB - Read & Write CSV Files with Ease
' https://youtu.be/9PWX89Sooac


Imports CsvHelper
Imports CsvHelper.Configuration
Imports CsvHelper.Configuration.Attributes
Imports Microsoft.Win32
Imports System.Globalization
Imports System.IO

Class MainWindow

    Private Shared ReadOnly OpenDialog As New OpenFileDialog() With {
        .Title = "Select a CSV file",
        .Filter = "CSV files (.csv)|*.csv"
    }

    Private Shared ReadOnly SaveDialog As New SaveFileDialog() With {
        .Title = "Save to a CSV file",
        .Filter = "CSV files (.csv)|*.csv"
    }

    Public Sub New()
        InitializeComponent()
    End Sub

    Private Sub ReadBtn_Click(sender As Object, e As RoutedEventArgs)
        If OpenDialog.ShowDialog() = True Then
            Using reader As New StreamReader(OpenDialog.FileName)
                Using csv As New CsvReader(reader, CultureInfo.InvariantCulture)

                    DataTable.ItemsSource = csv.GetRecords(Of Person)()

                    ' If you don't want to use a custom class, try this...
                    ' csv.GetRecords(Of Object)()

                End Using
            End Using
        End If
    End Sub

    Private Sub WriteBtn_Click(sender As Object, e As RoutedEventArgs)
        Dim persons As New List(Of Person)() From {
            New Person() With {
                .ID = 1,
                .Name = "John Doe",
                .Email = "johndoe@example.com",
                .PhoneNumber = "123-456-7890",
                .IsEmployed = True
            },
            New Person() With {
                .ID = 2,
                .Name = "Jane Smith",
                .Email = "janesmith@example.com",
                .PhoneNumber = "098-765-4321",
                .IsEmployed = False
            }
        }

        If SaveDialog.ShowDialog() = True Then
            Using writer As New StreamWriter(SaveDialog.FileName)
                Using csv As New CsvWriter(writer, CultureInfo.InvariantCulture)
                    csv.WriteRecords(persons)
                End Using
            End Using
        End If
    End Sub

    Private Sub EditBtn_Click(sender As Object, e As RoutedEventArgs)
        Dim newPersons As New List(Of Person)() From {
            New Person() With {
                .ID = 4,
                .Name = "Emma John",
                .Email = "emma@example.com",
                .PhoneNumber = "987-654-3210",
                .IsEmployed = False
            }
        }

        If OpenDialog.ShowDialog() = True Then
            Dim config As New CsvConfiguration(CultureInfo.InvariantCulture) With {
                .HasHeaderRecord = False
            }

            Using stream As FileStream = File.Open(OpenDialog.FileName, FileMode.Append)
                Using writer As New StreamWriter(stream)
                    Using csv As New CsvWriter(writer, config)
                        csv.WriteRecords(newPersons)
                    End Using
                End Using
            End Using
        End If
    End Sub
End Class

Public Class Person
    Public Property ID As Integer
    Public Property Name As String = ""
    Public Property Email As String = ""
    Public Property PhoneNumber As String = ""
    Public Property IsEmployed As Boolean
End Class

Public Class Person2
    Public Property ID As Integer

    <Name("Full Name")>
    Public Property Name As String = ""

    <Ignore>
    Public Property Email As String = "sample@example.com"

    <Index(2)>
    Public Property PhoneNumber As String = ""

    <Name("Employed?")>
    <BooleanTrueValues("yes")>
    <BooleanFalseValues("no")>
    Public Property IsEmployed As Boolean
End Class

XAML

<!-- AZUL CODING --------------------------------------- -->
<!-- .NET C#/VB - Read & Write CSV Files with Ease -->
<!-- https://youtu.be/9PWX89Sooac -->


<Window x:Class="CSVFiles.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:CSVFiles"
        mc:Ignorable="d"
        Title="CSV Files - Azul Coding" Width="450" SizeToContent="Height" ResizeMode="CanMinimize">
    <DockPanel Background="White">
        <Label DockPanel.Dock="Top" Content="CSV file manager" Padding="5,0,5,5" Margin="20" FontWeight="SemiBold" FontSize="16" BorderBrush="DodgerBlue" BorderThickness="0,0,0,2"/>
        <StackPanel DockPanel.Dock="Bottom" Margin="20" Orientation="Horizontal">
            <Button Name="ReadBtn" Padding="10,5" Margin="0,0,10,0" Background="#f0f0f0" Click="ReadBtn_Click">
                <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                    <Image Height="24" Width="24" Source="https://img.icons8.com/fluency/48/opened-folder.png"/>
                    <TextBlock Text="Read" VerticalAlignment="Center" FontSize="14" Margin="10,0,5,2"/>
                </StackPanel>
            </Button>
            <Button Name="WriteBtn" Padding="10,5" Margin="0,0,10,0" Background="#f0f0f0" Click="WriteBtn_Click">
                <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                    <Image Height="24" Width="24" Source="https://img.icons8.com/fluency/48/save.png"/>
                    <TextBlock Text="Write" VerticalAlignment="Center" FontSize="14" Margin="10,0,5,2"/>
                </StackPanel>
            </Button>
            <Button Name="EditBtn" Padding="10,5" Margin="0,0,10,0" Background="#f0f0f0" Click="EditBtn_Click">
                <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                    <Image Height="24" Width="24" Source="https://img.icons8.com/fluency/48/edit.png"/>
                    <TextBlock Text="Edit" VerticalAlignment="Center" FontSize="14" Margin="10,0,5,2"/>
                </StackPanel>
            </Button>
        </StackPanel>
        <DataGrid x:Name="DataTable" Margin="20,0" IsReadOnly="True"></DataGrid>
    </DockPanel>
</Window>