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.
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.
File.ReadLines
from the System.IO
namespace. This function does not load the entire file into memory at once.Split
on each line in the file. This does not correctly handle escaped comma characters.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.