Read Config Files in Visual Basic
Submitted by Yorkiebar on Monday, May 26, 2014 - 09:14.
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...
Config Path:
For the config path we first want to create a String variable to hold the path...
Now we can either set a default, hardcoded path...
Or we can create a temporary OpenFileDialog to allow the user to select their own config path...
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...
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.
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...
To MsgBox the name "Josh" form our properties list.
- Imports System.IO
- Dim path As String = ""
- path = "C:\Users\Josh\Desktop\config.txt"
- Using fo As New OpenFileDialog
- fo.RestoreDirectory = True
- fo.Filter = "Text Files | *.txt"
- fo.FilterIndex = 1
- fo.MultiSelect = False
- fo.ShowDialog()
- If Not (fo.FileName = Nothing) Then path = fo.FileName
- End Using
- Dim lines As New List(Of String)
- Using sr As New StreamReader(path)
- While (sr.peek <> -1)
- lines.add(sr.readline())
- End While
- End Using
- Private Function getProperty(ByVal prop As String, ByVal list As List(Of String))
- For Each item As String In list
- If (item.Split(":")(0) = prop) Then Return item.Split(":")(1)
- Next
- Return ""
- End Function
- MsgBox(getProperty("Name", list))
Add new comment
- 232 views