CSV. A comma-separated values file stores data—it separates each unit with a comma character. In C# we can use built-in methods like Split to parse CSV files.
For maximum performance, a method that handles each byte in a for-loop would be best. But for more clarity, calling the Split method on each line from the file is better.
First example. To run this example, be sure to change the path specified in the Main method to a CSV file that exists. The CSV file will be read and parsed.
using System;
using System.IO;
class Program
{
static void HandleFile(string path)
{
// Step 2: read each line individually with ReadLines.
foreach (string line in File.ReadLines(path))
{
// Step 3: split the line on a comma.
string[] parts = line.Split(',');
// Step 4: loop over the lines and do something with them.
foreach (string value in parts)
{
Console.WriteLine("PART: {0}", value);
}
}
}
static void Main()
{
// Step 1: specify the CSV file path.
HandleFile("programs/example.txt");
}
}PART: Field1
PART: Field2
PART: Field3
PART: Field4
PART: 100
PART: 200
PART: 300
Summary. There are many ways to handle CSV files in C# programs. With a File.ReadLines and Split, we can handle many files without using any external code.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 8, 2023 (new example).