C# .NET 中最简单的键/值对文件解析
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/284858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simplest possible key/value pair file parsing in .NET
提问by Hannes Landeholm
My project requires a file where I will store key/value pair data that should be able to be read and modified by the user. I want the program to just expect the keys to be there, and I want to parse them from the file as quickly as possible.
我的项目需要一个文件,我将在其中存储应该能够被用户读取和修改的键/值对数据。我希望程序只期望密钥在那里,并且我想尽快从文件中解析它们。
I could store them in XML, but XML is way to complex, and it would require traversing nodes, and child nodes and so on, all I want is some class that takes a file and generates key value pairs. I want as little error handling as possible, and I want it done with as little code as possible.
我可以将它们存储在 XML 中,但 XML 是一种复杂的方式,它需要遍历节点和子节点等,我想要的只是一些接受文件并生成键值对的类。我想要尽可能少的错误处理,并且我想要用尽可能少的代码来完成。
I could code a class like that myself, but I'd rather learn how it's don'e in the framework than inventing the wheel twice. Are there some built in magic class in .NET (3.5) that are able to do so?
我可以自己编写一个这样的类,但我宁愿了解它在框架中的作用,而不是两次发明轮子。.NET (3.5) 中是否有一些内置的魔法类可以这样做?
MagicClass kv = new MagicClass("Settings.ini"); // It doesn't neccesarily have to be an INI file, it can be any simple key/value pair format.
string Value1 = kv.get("Key1");
...
采纳答案by Nicholas Mancuso
Use the KeyValuePairclass for you Key and Value, then just serialize a Listto disk with an XMLSerializer.
为您的 Key 和 Value使用KeyValuePair类,然后使用XMLSerializer将List序列化到磁盘。
That would be the simplest approach I feel. You wouldn't have to worry about traversing nodes. Calling the Deserialize function will do that for you. The user could edit the values in the file if they wish also.
这将是我觉得最简单的方法。您不必担心遍历节点。调用 Deserialize 函数将为您做到这一点。如果他们愿意,用户也可以编辑文件中的值。
回答by Jb Evain
I don't know of any builtin class to parse ini file. I've used niniwhen needed to do so. It's licensed under the MIT/X11 license, so doesn't have any issue to be included in a closed source program.
我不知道有什么内置类可以解析 ini 文件。我在需要时使用了nini。它是在 MIT/X11 许可下获得许可的,因此没有任何问题可以包含在封闭源程序中。
It's very to use. So if you have a Settings.ini file formatted this way:
非常好用。因此,如果您有一个以这种方式格式化的 Settings.ini 文件:
[Configuration]
Name = Jb Evain
Phone = +330101010101
Using it would be as simple as:
使用它很简单:
var source = new IniConfigSource ("Settings.ini");
var config = source.Configs ["Configuration"];
string name = config.Get ("Name");
string phone = config.Get ("Phone");
回答by Jeff Kotula
Format the file this way:
以这种方式格式化文件:
key1=value1
key2=value2
Read the entire file into a string (there is a simple convenience function that does that, maybe in the File or string class), and call string.Split('='). Make sure you also call string.Trim() on each key and value as you traverse the list and pop each pair into a hashtable or dictionary.
将整个文件读入一个字符串(有一个简单的方便函数可以做到这一点,可能在 File 或 string 类中),然后调用 string.Split('=')。确保在遍历列表并将每对弹出到哈希表或字典中时,还对每个键和值调用 string.Trim()。
回答by Steven A. Lowe
if you want the user to be able to read and modify the file, i suggest a comma-delimited pair, one per line
如果您希望用户能够读取和修改文件,我建议使用逗号分隔的对,每行一个
key1,value1
key2,value2
...
parsing is simple: read the file, split at newline or comma, then take the elements in pairs
解析很简单:读取文件,在换行符或逗号处拆分,然后成对获取元素
回答by Kyght
If you're looking for a quick easy function and don't want to use .Net app\user config setting files or worry about serialization issues that sometimes occur of time.
如果您正在寻找快速简单的功能并且不想使用 .Net app\user 配置设置文件或担心有时会出现的序列化问题。
The following static function can load a file formatted like KEY=VALUE
.
以下静态函数可以加载格式为KEY=VALUE
.
public static Dictionary<string, string> LoadConfig(string settingfile)
{
var dic = new Dictionary<string, string>();
if (File.Exists(settingfile))
{
var settingdata = File.ReadAllLines(settingfile);
for (var i = 0; i < settingdata.Length; i++)
{
var setting = settingdata[i];
var sidx = setting.IndexOf("=");
if (sidx >= 0)
{
var skey = setting.Substring(0, sidx);
var svalue = setting.Substring(sidx+1);
if (!dic.ContainsKey(skey))
{
dic.Add(skey, svalue);
}
}
}
}
return dic;
}
Note: I'm using a Dictionary so keys must be unique, which is usually that case with setting.
注意:我使用的是字典,所以键必须是唯一的,这通常是设置的情况。
USAGE:
用法:
var settingfile = AssemblyDirectory + "\mycustom.setting";
var settingdata = LoadConfig(settingfile);
if (settingdata.ContainsKey("lastrundate"))
{
DateTime lout;
string svalue;
if (settingdata.TryGetValue("lastrundate", out svalue))
{
DateTime.TryParse(svalue, out lout);
lastrun = lout;
}
}