PCGuy13 PCGuy13 - 8 days ago 5
Vb.net Question

Edit a properties text file vb.net

I have a text file containing the properties for a virtual server running on my machine. I would like to be able to edit those properties from a GUI built with VB 2008. The Properties file is pre-generated with default values and I would like to change those values to fit my needs.

The Properties file is formatted as follows:

Item-One=ValueOne
Item-Two=ValueTwo
Item-Three=OtherLongValue
etc.


What I need is to be able to select the property based off it's name (Item-Two) and then remove the original value (which may be unknown) and place in my custom value. Values are String type.

I have already tried two suggestions, but neither achieve my goal.

Attempt1:
System.IO.File.WriteAllText(propName, System.IO.File.ReadAllText(propName).Replace("initial", "final"))

Attempt2:
Dim thefile As String = PropertyFileName
Dim lines() As String = System.IO.File.ReadAllLines(thefile)
lines(28) = "Item-Example=" + myValue
System.IO.File.WriteAllLines(thefile, lines)


Number One does not work because it requires me to know the original value, which I do not.
Number Two "works" but often adds new lines instead of replacing the old.

Answer

Here is a class I made.
It is also documented which should help with inteliSense.
Bellow I added some example of its usage.


SettingManager.vb

''' <summary>
''' Manages Settings which can be loaded and saved to a file specified
''' </summary>
''' <remarks></remarks>
Public Class SettingManager
    Private filePath As String
    Private prop As New Dictionary(Of String, String)

    ''' <summary>
    ''' Create a new SettingManager and loads settings from file specified.
    ''' If file specified doesnt exist, a new one is created upon save()
    ''' </summary>
    ''' <param name="filePath">Setting file to load</param>
    ''' <remarks></remarks>
    Sub New(ByVal filePath As String)
        Me.filePath = filePath
        If (Not System.IO.File.Exists(filePath)) Then
            Return
        End If
        Using reader As System.IO.StreamReader = New System.IO.StreamReader(filePath)
            Dim line As String
            line = reader.ReadLine()

            'Loop through the lines and add each setting to the dictionary: prop
            Do While (Not line Is Nothing)
                'Spit the line into setting name and value
                Dim tmp(2) As String
                tmp = line.Split("=")
                Me.AddSetting(tmp(0), tmp(1))
                line = reader.ReadLine()
            Loop
        End Using
    End Sub

    ''' <summary>
    ''' Get value of specified setting if exists.
    ''' If setting doesnt exist, KeyNotFound exception is thrown
    ''' </summary>
    ''' <param name="name">Name of setting</param>
    ''' <returns>Value of setting</returns>
    Function GetSetting(ByVal name As String) As String
        If (Not prop.ContainsKey(name)) Then
            Throw New KeyNotFoundException("Setting: " + name + " not found")
        End If
        Return prop(name)
    End Function

    ''' <summary>
    ''' Adds a new setting.
    ''' </summary>
    ''' <param name="name">Name of setting</param>
    ''' <param name="value">Value of setting</param>
    ''' <remarks>Save() function should be called to save changes</remarks>
    Sub AddSetting(ByVal name As String, ByVal value As String)
        If (prop.ContainsKey(name)) Then
            prop(name) = value
        Else
            prop.Add(name, value)
        End If
    End Sub

    ''' <summary>
    ''' Saves settings to file. Any new settings added are also saved
    ''' </summary>
    ''' <remarks></remarks>
    Sub Save()
        Using writer As System.IO.StreamWriter = New System.IO.StreamWriter(filePath)
            For Each kvp As KeyValuePair(Of String, String) In Me.prop
                writer.WriteLine(kvp.Key + "=" + kvp.Value)
            Next
        End Using
    End Sub
End Class

How to use:

  1. Create a new file in your project called SettingManager.vb
  2. Copy the code above into it

Example Usage

Dim sm As New SettingManager("settings.txt")

'Get Setting
Console.WriteLine(sm.GetSetting("Item-One")) 'Value-One

'Change setting
pm.AddSetting("Item-One", "different_value")
Console.WriteLine(sm.GetSetting("Item-One")) 'different_value

'Add new Setting
pm.AddSetting("name", "Krimson")
Console.WriteLine(sm.GetSetting("name")) 'Krimson

'Save any changes made
sm.Save()


Note: The code is not robust enough. For example if a value contains an =, errors might occur since there is no check implemented to prevent this. However, this should be a good starting point