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.
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.
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.
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 ModuleFIELD: 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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.