Tag Archives: csv file
C# || How To Parse A Delimited CSV File Using C#
The following is a module with functions which demonstrates how to parse a delimited CSV file using VB.NET.
This function parses a CSV file and returns its results as a List. Each List index represents a line in the CSV file, with each item in the list representing a record contained on that line.
The function demonstrated on this page uses FileIO.TextFieldParser to parse values in a CSV file.
Note: To use the function in this module, make sure you have a reference to ‘Microsoft.VisualBasic‘ in your project.
One way to do this is, in your Solution Explorer (where all the files are shown with your project), right click the ‘References‘ folder, click ‘Add Reference‘, then type ‘Microsoft.VisualBasic‘ in the search box, and add the reference titled Microsoft.VisualBasic in the results Tab.
1. Parse CSV File
The example below demonstrates the use of ‘Utils.Methods.ParseCsv‘ to parse a CSV file and return its results as a List.
The optional function parameter allows you to specify the delimiters. Default delimiter is a comma (,).
Sample CSV used in this example is the following:
1 2 3 4 5 6 |
Kenneth,Perkins,120 jefferson st.,Riverside, NJ, 08075 Jack,McGinnis,220 hobo Av.,Phila, PA,09119 "Jennifer ""Da Man""",Repici,120 Jefferson St.,Riverside, NJ,08075 Stephen,Tyler,"7452 Terrace ""At the Plaza"" road",SomeTown,SD, 91234 ,Blankman,,SomeTown, SD, 00298 "Joan ""the bone"", Anne",Jet,"9th, at Terrace plc",Desert City,CO,00123 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
// Parse CSV File // Read file into byte array byte[] fileBytes; // Parse the contents of the file into a list var fileContents = Utils.Methods.ParseCsv(fileBytes); // Display the contents of the file for (var lineIndex = 0; lineIndex < fileContents.Count; ++lineIndex) { var line = fileContents[lineIndex]; Console.WriteLine($"Line #{lineIndex + 1}"); foreach (var item in line) { Console.WriteLine($" Item: {item}"); } } // expected output: /* Line #1 Item: Kenneth Item: Perkins Item: 120 jefferson st. Item: Riverside Item: NJ Item: 08075 Line #2 Item: Jack Item: McGinnis Item: 220 hobo Av. Item: Phila Item: PA Item: 09119 Line #3 Item: Jennifer "Da Man" Item: Repici Item: 120 Jefferson St. Item: Riverside Item: NJ Item: 08075 Line #4 Item: Stephen Item: Tyler Item: 7452 Terrace "At the Plaza" road Item: SomeTown Item: SD Item: 91234 Line #5 Item: Item: Blankman Item: Item: SomeTown Item: SD Item: 00298 Line #6 Item: Joan "the bone", Anne Item: Jet Item: 9th, at Terrace plc Item: Desert City Item: CO Item: 00123 */ |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 14, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; using System.Linq; using System.Collections.Generic; namespace Utils { public static class Methods { /// <summary> /// Parses a Csv file and returns its results as a List. /// Each List index represents a line in the Csv file, with each /// item in the list representing a record contained on that line. /// </summary> /// <param name="fileBytes">The Csv file as a byte array</param> /// <param name="delimiters">The Csv data delimiter</param> /// <returns>The the file contents as a List</returns> public static List<List<string>> ParseCsv(byte[] fileBytes , string delimiters = ",") { var results = new List<List<string>>(); using (var stream = new System.IO.MemoryStream(fileBytes)) { using (var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(stream)) { parser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited; parser.Delimiters = delimiters.Select(letter => letter.ToString()).ToArray(); parser.HasFieldsEnclosedInQuotes = true; // Parse each line in the file while (!parser.EndOfData) { var currentLine = parser.ReadFields(); results.Add(currentLine.ToList()); } } } return results; } } }// http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 14, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; using System.Collections.Generic; public class Program { static void Main(string[] args) { try { // Read file into byte array byte[] fileBytes; // Parse the contents of the file into a list var fileContents = Utils.Methods.ParseCsv(fileBytes); // Display the contents of the file for (var lineIndex = 0; lineIndex < fileContents.Count; ++lineIndex) { var line = fileContents[lineIndex]; Display($"Line #{lineIndex + 1}"); foreach (var item in line) { Display($" Item: {item}"); } } } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Parse A Delimited CSV File Using VB.NET
The following is a module with functions which demonstrates how to parse a delimited CSV file using VB.NET.
The function demonstrated on this page uses FileIO.TextFieldParser to parse values in a CSV file.
This function parses a CSV file and returns its results as a List. Each List index represents a line in the CSV file, with each item in the list representing a record contained on that line.
1. Parse CSV File
The example below demonstrates the use of ‘Utils.ParseCsv‘ to parse a CSV file and return its results as a List.
The optional function parameter allows you to specify the delimiters. Default delimiter is a comma (,).
Sample CSV used in this example is the following:
1 2 3 4 5 6 |
Kenneth,Perkins,120 jefferson st.,Riverside, NJ, 08075 Jack,McGinnis,220 hobo Av.,Phila, PA,09119 "Jennifer ""Da Man""",Repici,120 Jefferson St.,Riverside, NJ,08075 Stephen,Tyler,"7452 Terrace ""At the Plaza"" road",SomeTown,SD, 91234 ,Blankman,,SomeTown, SD, 00298 "Joan ""the bone"", Anne",Jet,"9th, at Terrace plc",Desert City,CO,00123 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
' Parse CSV File ' Read file into byte array Dim fileBytes As Byte() ' Parse the contents of the file into a list Dim fileContents = Utils.ParseCsv(fileBytes) ' Display the contents of the file For lineIndex = 0 To fileContents.Count - 1 Dim line = fileContents(lineIndex) Debug.Print($"Line #{lineIndex + 1}") For Each item In line Debug.Print($" Item: {item}") Next Next ' expected output: ' Line #1 ' Item: Kenneth ' Item: Perkins ' Item: 120 jefferson st. ' Item: Riverside ' Item: NJ ' Item: 08075 ' Line #2 ' Item: Jack ' Item: McGinnis ' Item: 220 hobo Av. ' Item: Phila ' Item: PA ' Item: 09119 ' Line #3 ' Item: Jennifer "Da Man" ' Item: Repici ' Item: 120 Jefferson St. ' Item: Riverside ' Item: NJ ' Item: 08075 ' Line #4 ' Item: Stephen ' Item: Tyler ' Item: 7452 Terrace "At the Plaza" road ' Item: SomeTown ' Item: SD ' Item: 91234 ' Line #5 ' Item: ' Item: Blankman ' Item: ' Item: SomeTown ' Item: SD ' Item: 00298 ' Line #6 ' Item: Joan "the bone", Anne ' Item: Jet ' Item: 9th, at Terrace plc ' Item: Desert City ' Item: CO ' Item: 00123 |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Dec 2, 2020 ' Taken From: http://programmingnotes.org/ ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils ''' <summary> ''' Parses a Csv file and returns its results as a List. ''' Each List index represents a line in the Csv file, with each ''' item in the list representing a record contained on that line. ''' </summary> ''' <param name="fileBytes">The Csv file as a byte array</param> ''' <param name="delimiters">The Csv data delimiter</param> ''' <returns>The file contents as a List</returns> Public Function ParseCsv(fileBytes As Byte() _ , Optional delimiters As String = ",") As List(Of List(Of String)) Dim results = New List(Of List(Of String)) Using stream = New System.IO.MemoryStream(fileBytes) Using parser = New Microsoft.VisualBasic.FileIO.TextFieldParser(stream) parser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited parser.Delimiters = delimiters.Select(Function(letter) letter.ToString).ToArray parser.HasFieldsEnclosedInQuotes = True ' Parse each line in the file While Not parser.EndOfData Dim currentLine = parser.ReadFields results.Add(currentLine.ToList) End While End Using End Using Return results End Function End Module End Namespace ' http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Dec 2, 2020 ' Taken From: http://programmingnotes.org/ ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace ' ============================================================================ Option Strict On Option Explicit On Imports System Public Module Program Sub Main(args As String()) Try ' Read file into byte array Dim fileBytes As Byte() ' Parse the contents of the file into a list Dim fileContents = Utils.ParseCsv(fileBytes) ' Display the contents of the file For lineIndex = 0 To fileContents.Count - 1 Dim line = fileContents(lineIndex) Display($"Line #{lineIndex + 1}") For Each item In line Display($" Item: {item}") Next Next Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.