Home
Map
CSV Function ExampleUse the File.ReadLines function along with Split to parse fields contained within CSV files.
VB.NET
This page was last reviewed on Dec 8, 2023.
CSV. A comma-separated values file can be handled in a variety of ways in a VB.NET program. Often the best approach is to use the System.IO namespace and parse the file with String functions.
By calling Split on each line as we read it into memory, we can separate out fields. The strings returned could be added to a List or stored in a Class instance.
String Split
Example. To begin, make sure to change the path in the Main Sub to a CSV file that exists. The path is relative to the home directory on the computer.
Step 1 We call File.ReadLines from the System.IO namespace. This function does not load the entire file into memory at once.
File
Step 2 We call Split on each line in the file. This does not correctly handle escaped comma characters.
Step 3 We use a nested For Each loop to print out each part of the line to the console.
Console.WriteLine
Imports System.IO Module Module1 Sub HandleFile(path As String) ' Step 1: read lines from the file. For Each line in File.ReadLines(path) ' Step 2: separate each line on the comma char. Dim parts = line.Split(","c) ' Step 3: print out the parts of the line. For Each value in parts Console.WriteLine("FIELD: {0}", value) Next Next End Sub Sub Main() HandleFile("programs/example.txt") End Sub End Module
FIELD: Field1 FIELD: Field2 FIELD: Field3 FIELD: Field4 FIELD: 100 FIELD: 200 FIELD: 300
More complex formats can be handled in VB.NET, like JSON or even binary files, but CSV is often a good choice. It can be read and edited by humans, and processed with String methods in programs.
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).
Home
Changes
© 2007-2024 Sam Allen.