How to create a simple CSV Parser in C#

In this blog post, we will walk through the process of creating a straightforward CSV parser in C# and demonstrate how to map the CSV data to a Plain Old C# Object (POCO) class. CSV (Comma-Separated Values) files are a common way to store structured data, and being able to parse them in your C# applications can be quite handy.

Introduction

Before we dive into the code, let’s briefly discuss what this parser does and why it’s useful. The code we’ll be discussing is a C# program that reads a CSV file, extracts the data, and maps it to a POCO class. This allows you to work with CSV data more easily within your C# application.

Code Overview

Importing Necessary Libraries

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using System.Reflection;` 

The code starts by importing the required libraries for file handling and data manipulation.

The Student Class

public class Student
{
    public int ID { get; set; }
    public string FullName { get; set; }
    public int Age { get; set; }

    public override string ToString()
    {
        return string.Format(@"ID={0}  FullName={1} Age={2}", ID, FullName, Age);
    }
}

The Student class represents the structure of the data contained in the CSV file. It includes properties for ID, FullName, and Age, as well as an override of the ToString method for displaying the object’s data.

The CSVProvider Class

 public class CSVProvider : IDisposable, IEnumerable, IEnumerator
    {
        private string fileName = default(string);
        FileStream fsObject = null;
        StreamReader readerObject = null;
        private string currentLine = default(string);
        public CSVProvider(string fileName)
        {
            this.fileName = fileName;
            fsObject = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            readerObject = new StreamReader(fsObject);
            //To skip header line
            readerObject.ReadLine();
        }

        public void Dispose()
        {
            if (readerObject != null)
                readerObject.Close();
            if (fsObject != null)
                fsObject.Close();
        }

        public IEnumerator GetEnumerator()
        {
            return this;
        }
        public object Current
        {
            get
            {
                string[] split = currentLine.Split(',');
                return new Student
                {
                    ID = int.Parse(split[0]),
                    FullName = split[1],
                    Age = int.Parse(split[2])


                };

            }
        }

        public bool MoveNext()
        {
            currentLine = readerObject.ReadLine();
            return currentLine != null;
        }

        public void Reset()
        {
            this.currentLine = default(string);
        }

    }
}

The CSVProvider class is the heart of our CSV parsing operation. It implements the IDisposable, IEnumerable, and IEnumerator interfaces.

  • The fileName field stores the path to the CSV file.
  • fsObject is a FileStream object used for reading the file.
  • readerObject is a StreamReader used for reading lines from the file.
  • currentLine stores the current line being processed.

The constructor initializes these objects, opens the CSV file, and skips the header line. The class also includes methods for resource cleanup, iterating through the CSV data, and resetting the current line.

Usage in the Main Method

class Program
{
    static void Main(string[] args)
    {
        // Create an instance of the CSVProvider class, providing the CSV file path.
        CSVProvider csv = new CSVProvider(@"C:\Student.txt");
        
        // Iterate through the CSV data and print each item.
        foreach (var item in csv.OfType())
        {
            Console.WriteLine(item.ToString());
        }
        
        // Wait for user input before closing the console application.
        Console.ReadLine();
    }
}

In the Main method, we create an instance of the CSVProvider class, read and parse the CSV data, and then print each Student object to the console.

Conclusion

In this blog post, we’ve demonstrated how to create a simple CSV parser in C# and map the data to a POCO class. This can be a valuable tool for working with CSV data in your C# applications, making it easier to manipulate and utilize structured information from CSV files. You can take this basic example and build upon it to suit your specific needs for CSV data processing in C#.

إرسال تعليق

Please do not post any spam link in the comment box😊

أحدث أقدم

Blog ads

CodeGuru