我为我的应用程序创建了一个设置文件,如下所示:
username: ProGamingHun version: 1.0 maxmemory: 1GB minmemory: 512MB我想读取用户名,所以Dim username =在设置文件中:ProGamingHun,我该怎么做? 用户名是unknow leght,因为ProGamingHun是一个测试文本。 谢谢你的帮助。
I created a settings file for my application, like this:
username: ProGamingHun version: 1.0 maxmemory: 1GB minmemory: 512MBI want to read username, so Dim username = in the settings file: ProGamingHun, how can i do this? The username is unknow leght, because ProGamingHun is a test text. Thanks for helping.
最满意答案
我不相信,你发布的代码作为答案,正确解析文件。 你最好使用正则表达式:
Dim lines() As String = IO.File.ReadAllLines(SettingsRoot + "\config.cfg") Dim matches = lines.SelectMany(Function(line) Regex.Matches(line, "(.*): (.*)").Cast(Of Match)) Dim dictionary = matches.ToDictionary(Function(match) match.Groups(1).Value, Function(match) match.Groups(2).Value)dictionary现在将包含您的设置的键值对。 即使这不是您的原始问题,您也可以使用以下代码逐个显示在消息框中:
For Each setting In dictionary MessageBox.Show(setting.Key & "=" & setting.Value) Next不过,我建议您使用许多标准格式之一来保存设置。 这样,您可以使用现有库来解析它们:
XML: ConfigurationManager类 JSON: Json.NET INI: INI文件解析器编辑
要从字典中获取值到单个变量,请使用处理缺失键(设置)的dictionary.TryGetValue :
Dim username As String = Nothing dictionary.TryGetValue("username", username)I'm not convinced, the code you posted as answer, parses the file correctly. You're better off, using regular expressions instead:
Dim lines() As String = IO.File.ReadAllLines(SettingsRoot + "\config.cfg") Dim matches = lines.SelectMany(Function(line) Regex.Matches(line, "(.*): (.*)").Cast(Of Match)) Dim dictionary = matches.ToDictionary(Function(match) match.Groups(1).Value, Function(match) match.Groups(2).Value)dictionary will now contain the key-value pairs of your settings. Even though this wasn't your original question, you can display them in a message box one by one with the following code:
For Each setting In dictionary MessageBox.Show(setting.Key & "=" & setting.Value) NextNevertheless, I'd suggest you use one of many standard formats for saving settings. This way, you can use existing libraries to parse them:
XML: ConfigurationManager class JSON: Json.NET INI: INI File ParserEDIT
To get values from the dictionary into individual variables, use dictionary.TryGetValue which handles missing keys (settings):
Dim username As String = Nothing dictionary.TryGetValue("username", username)更多推荐
发布评论