Reading and Writing Settings.ini files in Vb.NET
Probably the easiest way to read and write settings.ini files in VB.NET is with a little bit of code from NuGET from MarioZ called https://github.com/MarioZ/MadMilkman.Ini
This is a section that I wrote using the examples to check and see if values exist, before writing a default settings file.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' Create new file with a default formatting. Dim file As New IniFile() 'The file exists If System.IO.File.Exists("settings.ini") Then file.Load("settings.ini") End If Dim section As IniSection = file.Sections.Add("Main") section.TrailingComment.Text = "Main Settings" Dim Values As String = file.Sections("Main")?.Keys("DataPath")?.Value If Values IsNot Nothing Then Console.WriteLine("it's not empty" & Values) Else Console.WriteLine("it's empty") ' Add new key and its value. Dim key As IniKey = section.Keys.Add("DataPath", "c:\temp\test.txt") ' Add leading comment. key.LeadingComment.Text = "Data path where the schedules live" ' Save file. file.Save("settings.ini") End If TextBox_Schedule_File.Text = file.Sections("Main")?.Keys("DataPath")?.Value End Sub
In keeping with the simple example, this writes a value to a file if the file exists.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button4.Click If (FolderBrowserDialog1.ShowDialog() = DialogResult.OK) Then TextBox1.Text = FolderBrowserDialog1.SelectedPath & "\test.txt" ' Create new file with a default formatting. Dim file As New IniFile() 'The file exists If System.IO.File.Exists("settings.ini") Then file.Load("settings.ini") file.Sections("Main").Keys("DataPath").Value = TextBox1.Text file.Save("settings.ini") End If End If End Sub
This entry was posted in Stories.