[英]Parsing key value pairs c#
我在嘗試從文本文件解析鍵值對時遇到問題。 我一直在尋找可以做我想做的事情的庫,因為我沒有能力創建一個可以做到這一點的類。
這是我的文件的開頭以及部分注釋掉的文本和鍵值對:
#!version:1.0.0.1
##File header "#!version:1.0.0.1" can not be edited or deleted, and must be placed in the first line.##
#######################################################################################
## Account1 Basic Settings ##
#######################################################################################
account.1.enable = 1
account.1.label = Front
account.1.display_name = Front
我想要做的是獲取這些值,並能夠將它們更新到文件中相同位置的文件中,因為這些文件需要保持人類可讀。
我已經研究過 Nini,因為這個庫似乎能夠做我想做的事情,但是我繼續遇到的錯誤是基於我文件的第 1 行,因為它不是鍵值對。
Expected assignment operator (=) - Line: 1, Position: 19.
我通讀了 Nini 的源代碼,似乎有一種方法可以讓讀者使用 Mysqlstyle,它會使用“#”作為注釋,但我不確定如何調整它,或者它是否按原樣自動完成完全在我的頭上。
我知道我的文件不是合法的 ini 文件,並且 Nini 庫在搜索鍵值對所在的部分時可能存在限制。
我試圖用來解析和顯示此文本以使用 Nini 進行編輯的代碼如下:
public void EditCFG(string file)
{
if (!string.IsNullOrWhiteSpace(file))
{
IniConfigSource inifile = new IniConfigSource(file);
account_1_display_name.Text = inifile.Configs[""].Get("account.1.display.name");
}
}
有人可以指出我正確的方向嗎?
感謝@rowland-shaw,我找到了解決方案:
private IConfigSource source = null;
public void EditCFG(string file)
{
if (!string.IsNullOrWhiteSpace(file))
{
IniDocument inifile = new IniDocument(file, IniFileType.MysqlStyle);
source = new IniConfigSource(inifile);
account_1_display_name.Text = source.Configs["account"].Get("account.1.display_name");
}
}
然而,這並不完全是答案。 我還必須在文件中實現部分。 在測試我用更新的文本抓取這些文件的設備后,一切都成功了。
如果這就是文件中的格式( key = value
和 # 用於注釋),您可以執行以下操作(c# 偽代碼,您可以自己做一些瑣碎的事情):
Dictionary<string, string> dictionary;
foreach(string line in file)
{
if(string.IsNullOrWhiteSpace(line)) continue;
// Remove extra spaces
line = line.Trim();
if(line[0] == '#') continue;
string[] kvp = line.Split('=');
dictionary[kvp[0].Trim()] = kvp[1].Trim(); // kvp[0] = key, kvp[1] = value
}
然后您可以使用創建的字典,如account_1_display_name.Text = dictionary["account.1.display.name"];
您需要指定IniFileType
,即:
IniConfigSource inifile = new IniConfigSource(file, IniFileType.MysqlStyle);
長示例:
IniDocument inifile = new IniDocument(file, IniFileType.MysqlStyle);
IniConfigSource source = new IniConfigSource(inifile);
我可以推薦我的庫Nager.ConfigParser,您可以通過 nuget 輕松獲取它們。
這是您的配置示例
var config = "#comment1\r\naccount.1.enable = 1\r\naccount.1.label = Front";
var configConvert = new ConfigConvert();
var item = configConvert.DeserializeObject<AccountCollection>(config);
public class AccountCollection
{
[ConfigKey("account.")]
[ConfigArray]
public Account[] Accounts { get; set; }
}
public class Account : ConfigArrayElement
{
public int Enable { get; set; }
public string Label { get; set; }
[ConfigKey("display_name")]
public string DisplayName { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.