【问题标题】:How to read from file and supply it to variables如何从文件中读取并将其提供给变量
【发布时间】:2015-08-23 19:14:51
【问题描述】:

我正在制作一个游戏引擎。我需要将一个文本文件加载到我的程序中,然后将每一行排序为一个特定的值。 我需要将每一行提取到特定的字符串中,以便稍后在程序中读取。

这是配置文件的外观:

title=HelloWorld
developer=MightyOnes
config=classic

代码会将title= 提取成一个字符串,上面写着HelloWorld。 其余的也一样。开发人员将是MightyOnes。我想你现在明白了。

【问题讨论】:

  • 特殊配置文件是什么意思
  • 这是一个文本文件,基本上是一个值列表。
  • 文件的内容是什么?它有变化吗?它看起来怎么样?
  • 您需要填写预设数量的值。它看起来像上面。我计算了 20-30 个不同的值,您可以从中选择。

标签: vb.net config


【解决方案1】:

您真正需要的是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

【讨论】:

  • 非常好的答案。谢谢。
猜你喜欢
  • 2019-12-22
  • 1970-01-01
  • 2019-10-28
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2010-11-23
  • 1970-01-01
  • 2011-06-12
相关资源
最近更新 更多