Vb.net读取设置文件(Vb.net read settings file)

编程入门 行业动态 更新时间:2024-10-26 22:25:37
Vb.net读取设置文件(Vb.net read settings file)

我为我的应用程序创建了一个设置文件,如下所示:

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: 512MB

I 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) Next

Nevertheless, 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 Parser

EDIT

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)

更多推荐

本文发布于:2023-04-29 11:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336264.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   net   Vb   file   settings

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!