Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

vb.net - How to read from file and supply it to variables

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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	est.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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...