How to read from file and supply it to variables

2019-09-20 08:35发布

问题:

I am making a game engine. I need to load a text file into my program and then sort each line into a specific value. I need to extract each line into specific string so I can read it in the program later.

This is how the config file looks:

title=HelloWorld
developer=MightyOnes
config=classic

And the code would extract title= into a string that says HelloWorld. Same for the rest. Developer would be MightyOnes. I think you got it by now.

回答1:

What you really need is a Dictionary. A dictionary can hold key-value pairs, which can later be retrieved by key name.

Dim KeyValues As Dictionary(Of String, String)

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    '' to fill the dictionary
    KeyValues = New Dictionary(Of String, String)
    Dim fileContents = IO.File.ReadAllLines("C:\Test\test.txt")  '-- replace with your config file name
    For Each line In fileContents
        Dim kv = Split(line, "=", 2)
        KeyValues.Add(kv(0), kv(1))
    Next

    '' to get a particular value from dictionary, say get value of "developer"
    Dim value As String = KeyValues("developer")
    MessageBox.Show(value)

End Sub


标签: vb.net config