Question Read and write in INI file

Nisse

New member
Joined
Dec 29, 2010
Messages
2
Programming Experience
Beginner
Hi all, i am using VB2008 to develop a Settings program for my game Lined World, creating with Game Maker. I've created a settings.ini:

[screen]
fullscreen=(off or on)
resolution=(800x600 or 1024x768)
[game]
controlset=(1 or 2)
music=(on or off)

answers are depending on settings

now, i wanna create in the settings app the following:
"fullscreen" (radiobutton-on & radiobutton-off)
"resolution" (radiobutton 800x600 & radiobutton 1024x768
"controls" (radiobutton AWSD & radiobutton arrows
"music" (radiobutton on & radiobutton off)

if radiobutton fullscreen is on, [screen]fullscreen must be on, and if turned to off, the INI value should be "off".

could anybody help me?
thx in advance!:cool:
 

MattP

Well-known member
Joined
Feb 29, 2008
Messages
1,206
Location
WY, USA
Programming Experience
5-10
I hate working with INI files and would suggest looking into XML as an alternative.

Here's the INI file I'm working with:

[screen]
fullscreen=off
resolution=800x600

[game]
controlset=2
music=on

Here's the class to Read/Write values in the file:

VB.NET:
Public Class IniFile

    Private Declare Ansi Function GetPrivateProfileString Lib "kernel32.dll" Alias "GetPrivateProfileStringA" _
        (ByVal lpApplicationName As String, _
         ByVal lpKeyName As String, _
         ByVal lpDefault As String, _
         ByVal lpReturnedString As System.Text.StringBuilder, _
         ByVal nSize As Integer, _
         ByVal lpFileName As String) _
     As Integer

    Private Declare Ansi Function WritePrivateProfileString Lib "kernel32.dll" Alias "WritePrivateProfileStringA" _
        (ByVal lpApplicationName As String, _
         ByVal lpKeyName As String, _
         ByVal lpString As String, _
         ByVal lpFileName As String) _
    As Integer

    Public Property Path As String

    ''' <summary>
    ''' IniFile Constructor
    ''' </summary>
    ''' <param name="IniPath">The path to the INI file.</param>
    Public Sub New(ByVal IniPath As String)
        _Path = IniPath
    End Sub

    ''' <summary>
    ''' Read value from INI file
    ''' </summary>
    ''' <param name="section">The section of the file to look in</param>
    ''' <param name="key">The key in the section to look for</param>
    Public Function ReadValue(ByVal section As String, ByVal key As String) As String
        Dim sb As New System.Text.StringBuilder(255)
        Dim i = GetPrivateProfileString(section, key, "", sb, 255, Path)
        Return sb.ToString()
    End Function

    ''' <summary>
    ''' Write value to INI file
    ''' </summary>
    ''' <param name="section">The section of the file to write in</param>
    ''' <param name="key">The key in the section to write</param>
    ''' <param name="value">The value to write for the key</param>
    Public Sub WriteValue(ByVal section As String, ByVal key As String, ByVal value As String)
        WritePrivateProfileString(section, key, value, Path)
    End Sub

End Class

Here's an example of reading/manipulating the file:

VB.NET:
        Dim ini As New IniFile("C:\Temp\TheFile.ini")

        Dim res = ini.ReadValue("screen", "resolution")
        Dim ctrlSet = ini.ReadValue("game", "controlset")
        ini.WriteValue("game", "music", "off")
 

Nisse

New member
Joined
Dec 29, 2010
Messages
2
Programming Experience
Beginner
???

i dont really understand where to put that or something... im just a beginner after all... :confused: =/

could you post a little example maybe? i know XML is better for VB, but i dont believe Game Maker 8 Pro supports that...
 

MattP

Well-known member
Joined
Feb 29, 2008
Messages
1,206
Location
WY, USA
Programming Experience
5-10
1. Create a new program for testing.

2. Add a class to your project called IniFile.

3. Copy/Paste the class from above in it.

4. Double click on your form and paste in this code for the Form1.Load event (Change the path to the ini file to match the one you want to read.)

VB.NET:
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim ini As New IniFile("C:\Temp\TheFile.ini")

        Dim res = ini.ReadValue("screen", "resolution")
        MessageBox.Show(String.Format("The current resolution is {0}", res))

        Dim ctrlSet = ini.ReadValue("game", "controlset")
        MessageBox.Show(String.Format("The current controlset is {0}", ctrlSet))

        ini.WriteValue("game", "music", "off")
        MessageBox.Show("Music has been set to off")
    End Sub

5. Run the program and see what happens

6. Apply the logic to the areas where you need to read/write INI values in your program.
 

GeoffLondon

New member
Joined
Mar 27, 2013
Messages
1
Location
London, UK
Programming Experience
10+
Had to tweak MattP's Inifile class to get it to work

MattP,

This was a great post.

To make it work I had to modify your class a little bit, in relation to declaring _Path as a private string, and changing how the public Path was declared (but not actually used, even in your version).

VB.NET:
Public Class Inifile
    REM Got this from MattP in this forum
    REM http://www.vbdotnetforums.com/vb-net-general-discussion/45603-read-write-ini-file.html
 
    Private _Path As String
 
    Private Declare Ansi Function GetPrivateProfileString Lib "kernel32.dll" Alias "GetPrivateProfileStringA" _
        (ByVal lpApplicationName As String, _
         ByVal lpKeyName As String, _
         ByVal lpDefault As String, _
         ByVal lpReturnedString As System.Text.StringBuilder, _
         ByVal nSize As Integer, _
         ByVal lpFileName As String) _
     As Integer
 
    Private Declare Ansi Function WritePrivateProfileString Lib "kernel32.dll" Alias "WritePrivateProfileStringA" _
        (ByVal lpApplicationName As String, _
         ByVal lpKeyName As String, _
         ByVal lpString As String, _
         ByVal lpFileName As String) _
    As Integer
 
    Public Path() As String
 
    ''' <summary>
    ''' IniFile Constructor
    ''' </summary>
    ''' <param name="IniPath">The path to the INI file.</param>
    Public Sub New(ByVal IniPath As String)
        _Path = IniPath
    End Sub
 
    ''' <summary>
    ''' Read value from INI file
    ''' </summary>
    ''' <param name="section">The section of the file to look in</param>
    ''' <param name="key">The key in the section to look for</param>
    Public Function ReadValue(ByVal section As String, ByVal key As String) As String
        Dim sb As New System.Text.StringBuilder(255)
        Dim i As Integer = GetPrivateProfileString(section, key, "", sb, 255, _Path)
        Return sb.ToString()
    End Function
 
    ''' <summary>
    ''' Write value to INI file
    ''' </summary>
    ''' <param name="section">The section of the file to write in</param>
    ''' <param name="key">The key in the section to write</param>
    ''' <param name="value">The value to write for the key</param>
    Public Sub WriteValue(ByVal section As String, ByVal key As String, ByVal value As String)
        WritePrivateProfileString(section, key, value, _Path)
    End Sub
 
End Class

Geoff
London UK
 

Herman

Well-known member
Joined
Oct 18, 2011
Messages
882
Location
Montreal, QC, CA
Programming Experience
10+
Forget all of the above and use My.Settings inside visual studio, you have no reading or writing to do, everything is done for you, and your config files go to where they should be (in the user's profile Application Data folder).

EDIT: Upon review I see now that you are stuck with another application's file format. In that case I suggest using the method above.
 

Herman

Well-known member
Joined
Oct 18, 2011
Messages
882
Location
Montreal, QC, CA
Programming Experience
10+
Also, personally I would load and write all the settings at once, and expose a collection for the settings.

Public Class IniFile
    Private Declare Ansi Function WritePrivateProfileString Lib "kernel32.dll" Alias "WritePrivateProfileStringA" _
    (ByVal lpApplicationName As String, _
     ByVal lpKeyName As String, _
     ByVal lpString As String, _
     ByVal lpFileName As String) _
    As Integer

    Public Class UserSetting
        Public Property Section As String
        Public Property Key As String
        Public Property Value As String
    End Class

    Public Property Settings As New List(Of UserSetting)

    Private IniPath As String = ""

    Public Sub New(ByVal FilePath As String)
        IniPath = FilePath

        LoadIni()
    End Sub

    Private Sub LoadIni()
        Try
            Dim Lines As String() = IO.File.ReadAllLines(IniPath)

            Dim CurrentSection As String = ""
            For Each Line In Lines
                Line = Line.Trim
                If Line.Length > 0 Then
                    If Line.First = "[" Then
                        If Line.Last = "]" Then
                            CurrentSection = Line.Substring(1, Line.Length - 2)
                        Else
                            Throw New ArgumentException
                        End If
                    ElseIf Line.Contains("=") Then
                        Dim KeyValue As String() = Line.Split("=")
                        Settings.Add(New UserSetting With {.Section = CurrentSection,
                                                           .Key = KeyValue(0),
                                                           .Value = KeyValue(1)})
                    End If
                End If
            Next
        Catch ex As Exception
            MsgBox(ex.Message & vbCrLf & ex.StackTrace, MsgBoxStyle.Exclamation, "Error!")
        End Try
    End Sub

    Public Sub SaveSettings()
        Dim CurrentSection As String = ""

        For Each Setting In Settings
            If Not CurrentSection = Setting.Section Then
                CurrentSection = Setting.Section
            End If
            WritePrivateProfileString(Setting.Section, Setting.Key, Setting.Value, IniPath)
        Next
    End Sub

End Class
 
Top Bottom