Read Config Files in Visual Basic

Introduction: This tutorial is on how to use config files in your own Visual Basic applications. Design: There is no specific design required for this tutorial, however if you want a button to begin the process, feel free. Imports: Before we begin, we must import System.IO to read files from our computers filesystem...
  1. Imports System.IO
Config Path: For the config path we first want to create a String variable to hold the path...
  1. Dim path As String = ""
Now we can either set a default, hardcoded path...
  1. path = "C:\Users\Josh\Desktop\config.txt"
Or we can create a temporary OpenFileDialog to allow the user to select their own config path...
  1. Using fo As New OpenFileDialog
  2. fo.RestoreDirectory = True
  3. fo.Filter = "Text Files | *.txt"
  4. fo.FilterIndex = 1
  5. fo.MultiSelect = False
  6. fo.ShowDialog()
  7. If Not (fo.FileName = Nothing) Then path = fo.FileName
  8. End Using
Reading Config: Now here's the bit where we want to put our import to use. We want to create a new String list, and add each line from our config file to the list...
  1. Dim lines As New List(Of String)
  2. Using sr As New StreamReader(path)
  3. While (sr.peek <> -1)
  4. lines.add(sr.readline())
  5. End While
  6. End Using
Getting Property Function: We are going to create a function to return the property of a setting/value held within our config, and now our 'lists' object as well.
  1. Private Function getProperty(ByVal prop As String, ByVal list As List(Of String))
  2. For Each item As String In list
  3. If (item.Split(":")(0) = prop) Then Return item.Split(":")(1)
  4. Next
  5. Return ""
  6. End Function
This function takes two parameters, the property name, and the list of properties. It then iterates through the list until it finds the property and returns the right side of the line - the value. In case you didn't already realise, our config would look something like this; Username:Yorkiebar Name:Josh Then we could use our new function like...
  1. MsgBox(getProperty("Name", list))
To MsgBox the name "Josh" form our properties list.

Add new comment