In this article, we will discuss working with CSV files in C#. Working with CSV files in C# can be a very useful and important skill for developers who work with data. CSV, or Comma-Separated Values, is a file format used to store data in a structured way. It is widely used in various fields such as finance, sales, marketing, and research. In this article, we will discuss how to work with CSV files in C#. Analyzing and creating Comma-Separated Values (CSV) documents is a simpler way to obtain information about your software percentage. Several tools, like Microsoft Excel, make it simple to read and write CSV files.
Different Package to use CSV File in C#:
In C#, you can use different packages to work with CSV files. Here are some popular packages you can use:
System.IO : The System.IO package in C# provides a variety of classes and methods for working with files, including CSV files.
CsvHelper: CsvHelper is a powerful and easy-to-use package that allows you to read and write CSV files. It has many features such as automatic type conversion, header mapping, and more.
Microsoft.VisualBasic.FileIO: This package provides a TextFieldParser class that allows you to read CSV files and other delimited text files in a very simple and efficient way. It supports both reading and writing CSV files.
IronXL.Excel: The ironXL package is a C# library that provides an API for working with Excel files. However, it also provides support for working with CSV files, which can be useful for scenarios where you need to read or write data to a file in a simple, text-based format.
To install any library just Right-click on your project in the Solution Explorer and select "Manage NuGet Packages" and then search for any package which you want to use.
In this article, we are simply using System.IO package to CSV file in C#. You can choose any package according to your wish.
What is a CSV file?
As mentioned earlier, CSV stands for Comma-Separated Values. It is a file format used to store data in a structured way. Each row of a CSV file represents a record, and each column represents a field of the record. Fields are separated by commas, and records are separated by newlines. CSV files are often used for data exchange between different software systems and can be opened and edited using spreadsheet software such as Microsoft Excel.
Here is an example of a simple CSV file:
Name, Age, Gender
David, 35, Male
John, 25, Male
Smith, 55, Male
Sara, 32, Female
Lisa, 30, Female
Tom, 45, Male
Daisy, 32, Female
In this example, we have three fields: Name, Age, and Gender. Each row represents a record, and the fields of each record are separated by commas.
As you can see give below screenshot showing what our CSV file data looks like:
Reading CSV Files in C#:
To read a CSV file in C#, we can use the StreamReader class. The StreamReader class allows us to read text from a file.
Here is an example how of to read a CSV file:
Example:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
// Open the file using a StreamReader
using (var reader = new StreamReader("data.csv"))
{
// Read the rest of the file
while (!reader.EndOfStream)
{
// Read the first line of the file
var line = reader.ReadLine();
// Split the data line into an array of values
var values = line.Split(',');
foreach (var value in values)
{
Console.Write(value + " ");
}
Console.WriteLine();
}
}
}
}
In this example, we use the StreamReader class to read the contents of the data.csv file. The while loop reads each line of the file until the end is reached. The ReadLine() method reads a line of text from the file and stores it in the line variable. The Split() method is used to split the line into an array of strings using the comma character as a separator. The foreach loop is used to iterate over the values in the array and print them to the console.
After the successful execution of the project, here is what our output look like:
Output:
Writing CSV Files in C#:
To write a CSV file in C#, we can use the StreamWriter class. The StreamWriter class allows us to write text to a file.
Here is an example how of writing a CSV file:
Example:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
// Open the file using a StreamWriter
using (var writer = new StreamWriter("output.csv"))
{
// Write the header line
writer.WriteLine("Name,Age,Gender");
// Write some data lines
writer.WriteLine("John,25,Male");
writer.WriteLine("Sara,32,Female");
writer.WriteLine("Tom,45,Male");
}
}
}
In this example, we use the StreamWriter class to write the contents of the CSV file. The WriteLine() method is used to write a line of text to the file. Each line represents a record, and the fields of each record are separated by commas.
After the successful execution of the project, here is what our output look like:
Output:
Parse CSV files in C#:
A CSV (Comma Separated Values) file parser in C# is a program or code snippet that reads a CSV file and converts it into a structured format, such as an array, list, or table, that can be processed or manipulated by a computer program. A CSV file is a plain text file that consists of lines of data, where each line represents a record or row of data, and the values in each line are separated by commas or other delimiters.
A CSV file parser in C# typically involves the following steps:
Reading the CSV file line by line.
Splitting each line into separate fields based on the delimiter (usually a comma).
Converting each field into the appropriate data type (e.g. string, integer, date, etc.).
Storing the data in a data structure, such as an array, list, or table.
Here's an example of a simple CSV parser in C#:
Example:
using Microsoft.VisualBasic.FileIO;
using System.Collections.Generic;
// Specify the path to your CSV file
string csvFilePath = @"C:\path\to\your\file.csv";
// Create a list to store the parsed data
List<string[]> parsedData = new List<string[]>();
// Create a TextFieldParser object and set its properties
TextFieldParser parser = new TextFieldParser(csvFilePath);
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
// Read the CSV file line by line
while (!parser.EndOfData)
{
//
Parse the current line and add it to the list
string[] fields = parser.ReadFields();
parsedData.Add(fields);
}
// Close the TextFieldParser object
parser.Close();
// Now you can use the parsed data as needed
foreach (string[] fields in parsedData)
{
// Do something with the fields
}
In this example, we create a TextFieldParser object and set its properties to treat the file as a delimited file with commas as the delimiter. Then we use a while loop to read the file line by line, parsing each line into an array of fields using the ReadFields() method. Finally, we add each array of fields to a list for later use.
Conclusion:
In this article, we understand the concept of CSV Reader in C# through the definition, syntax, and working of CSV Reader through programming examples and their outputs and the advantages of using CSV Reader in our program to read a file in CSV format. CSV Reader is a simple library that is lightweight and open source that can read the data in CSV format from text files and strings.
Hope you enjoyed reading this article and found it useful. Please share your thoughts and recommendations in the comment section below.
Share This Post
Support Me