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.
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.
string
containing the path of the CSV file (relative to the home directory) we want to parse.File.ReadLines
, we handle each line individually, without loading the entire file into an array at once.Split
to separate the line on all the comma characters. This does not handle escaped characters.foreach
-loop, we print out each individual field within the line of the CSV file.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
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.