如何从文件中读取并将其提供给变量
How to read from file and supply it to variables
我正在制作游戏引擎。我需要将一个文本文件加载到我的程序中,然后将每一行排序为特定值。
我需要将每一行提取到特定的字符串中,以便稍后在程序中读取它。
这是配置文件的样子:
title=HelloWorld
developer=MightyOnes
config=classic
代码会将 title=
提取到一个表示 HelloWorld
的字符串中。
其余的也一样。开发人员将是 MightyOnes
。我想你现在已经明白了。
你真正需要的是Dictionary
。字典可以保存键值对,以后可以通过键名检索。
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
我正在制作游戏引擎。我需要将一个文本文件加载到我的程序中,然后将每一行排序为特定值。 我需要将每一行提取到特定的字符串中,以便稍后在程序中读取它。
这是配置文件的样子:
title=HelloWorld
developer=MightyOnes
config=classic
代码会将 title=
提取到一个表示 HelloWorld
的字符串中。
其余的也一样。开发人员将是 MightyOnes
。我想你现在已经明白了。
你真正需要的是Dictionary
。字典可以保存键值对,以后可以通过键名检索。
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