.NET 中最简单的键/值对文件解析

发布于 2024-07-08 03:09:49 字数 470 浏览 6 评论 0原文

我的项目需要一个文件,我将在其中存储用户应该能够读取和修改的键/值对数据。 我希望程序只期望键在那里,并且我想尽快从文件中解析它们。

我可以将它们存储在 XML 中,但是 XML 太复杂了,它需要遍历节点和子节点等等,我想要的只是一些接受文件并生成键值对的类。 我希望尽可能少地处理错误,并且希望用尽可能少的代码来完成它。

我可以自己编写这样的类,但我宁愿了解它在框架中的工作原理,也不愿重复发明轮子。 .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");
...

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.

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?

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");
...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

痴骨ら 2024-07-15 03:09:49

如果您正在寻找快速简单的功能并且不想使用.Net应用程序\用户配置设置文件或担心有时会发生的序列化问题。

以下静态函数可以加载 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;
}

注意:我使用的是字典,因此键必须是唯一的,这通常是设置的情况。

用法:

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;
    }
}

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.

The following static function can load a file formatted like 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;
    }
}
莳間冲淡了誓言ζ 2024-07-15 03:09:49

使用 KeyValuePair 类作为键和值,然后序列化一个 < a href="http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx" rel="noreferrer">列表 到磁盘,并带有 列表 到磁盘。 microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx" rel="noreferrer">XMLSerializer。

这将是我认为最简单的方法。 您不必担心遍历节点。 调用反序列化函数将为您完成此操作。 如果用户愿意,也可以编辑文件中的值。

Use the KeyValuePair class for you Key and Value, then just serialize a List to disk with an XMLSerializer.

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.

故事与诗 2024-07-15 03:09:49

我不知道有任何内置类来解析 ini 文件。 我在需要时使用了 nini 。 它是根据 MIT/X11 许可证获得许可的,因此包含在闭源程序中不存在任何问题。

非常好用。 因此,如果您有一个以这种方式格式化的 Settings.ini 文件:

[Configuration]
Name = Jb Evain
Phone = +330101010101

使用它就像这样简单:

var source = new IniConfigSource ("Settings.ini");
var config = source.Configs ["Configuration"];

string name = config.Get ("Name");
string phone = config.Get ("Phone");

I don't know of any builtin class to parse ini file. I've used nini when 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.

It's very to use. So if you have a Settings.ini file formatted this way:

[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");
酷炫老祖宗 2024-07-15 03:09:49

如果您希望用户能够读取和修改文件,我建议使用逗号分隔对,每行一个

key1,value1
key2,value2
...

解析很简单:读取文件,在换行符或逗号处拆分,然后成对获取元素

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

财迷小姐 2024-07-15 03:09:49

以这种方式格式化文件:

key1=value1
key2=value2

将整个文件读入字符串(有一个简单的便利函数可以做到这一点,可能在 File 或 string 类中),然后调用 string.Split('=')。 确保在遍历列表并将每对弹出到哈希表或字典时对每个键和值调用 string.Trim() 。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文