.NET 是否有与 Java 的 .properties 文件等效的文件?

发布于 2024-08-20 02:01:02 字数 508 浏览 6 评论 0原文

为了帮助大家记住,Java 提供了这些扩展名为“.properties”的文件,它们基本上是一个充满键值对的 ASCII 文本文件。该框架有一些非常简单的方法可以将该文件吸入(本质上)一个奇特的哈希映射中。

两大优势(在我看来)是手动编辑和阅读/写作都非常容易。

.NET 是否有同等功能?当然,我可以对 XML 文件执行相同的操作,但我不想手动输入所有这些尖括号,如果您知道我的意思的话。此外,一种将所有数据在一行中吸入内存中数据结构的方法也很好。

(侧边栏:我有点不敢相信这里还没有问过这个问题,但我找不到这样的问题。)

编辑:

为了回答某些评论暗示的问题,我不是在寻找专门读取 .NET 下的 java .properties 文件的方法,我正在寻找 .NET 宇宙中的功能等效项。 (我希望它不是基于 XML 的,显然忘记了我们正在谈论的是 .NET。)

而且,虽然配置文件是关闭,但我需要存储的方法一些任意字符串,而不是应用程序配置信息,因此配置文件的焦点和设计似乎不合理。

To jog everyone's memory, Java has these files with an extension of ".properties", which are basically an ASCII text file full of key-value pairs. The framework has some really easy ways to suck that file into (essentially) a fancy hashmap.

The two big advantages (as I see it) being extreme ease of both hand-editing and reading/writing.

Does .NET have an equivalent baked in? Sure, I could do the same with an XML file, but I'd rather not have to hand type all those angle brackets, if you know what I mean. Also, a way to suck all the data into a data structure in memory in one line is nice too.

(Sidebar: I kind of can't believe this hasn't been asked here already, but I couldn't find such a question.)

Edit:

To answer the question implied by some of the comments, I'm not looking for a way to specifically read java .properties files under .NET, I'm looking for the functional equivalent in the .NET universe. (And I was hoping that it wouldn't be XML-based, having apparently forgotten that this is .NET we're talking about.)

And, while config files are close, I need way to store some arbitrary strings, not app config information, so the focus and design of config files seemed off-base.

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

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

发布评论

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

评论(6

小女人ら 2024-08-27 02:01:02

您可以使用内置的 设置文件(在VS中,添加一个新的“设置文件”) - 但它仍然是基于XML的。

您可以使用自动生成的 Settings 类访问设置,甚至可以更新它们并将它们保存回配置文件 - 所有这些都无需编写任何样板代码。这些设置是强类型的,可以指定为“用户”(保存到用户的应用程序数据文件夹)或“应用程序”(保存到与正在运行的 exe 相同的文件夹)。

You can achieve a similar piece of functionality to properties files using the built in settings files (in VS, add a new "Settings file") - but it is still XML based.

You can access the settings using the auto-generated Settings class, and even update them and save them back to the config file - all without writing any of the boilerplate code. The settings are strongly-types, and can be specified as "User" (saved to the user's Application Data folder) or "Application" (saved to the same folder as the running exe).

假装爱人 2024-08-27 02:01:02

.NET 方法是使用配置文件。 .NET 框架甚至提供
用于使用它们的 API

The .NET way is to use a configuration file. The .NET framework even offers
an API for working with them.

荒路情人 2024-08-27 02:01:02

名为 nini 的第三方组件,可以在 sourceforge.net 找到

例如:

using Nini;
using Nini.Config;

namespace niniDemo{
   public class niniDemoClass{
       public bool LoadIni(){
            string configFileName = "demo.ini";
            IniConfigSource configSource = new IniConfigSource(configFileName);

            IConfig demoConfigSection = configSource.Configs["Demo"];
            string demoVal = demoConfigSection.Get("demoVal", string.Empty);
       }
   }

}

有一个 示例的“demo.ini”文件为:

[Demo]
demoVal = foobar

如果 demoVal 的值为 null 或空,则默认为 string.Empty

There is a third party component called nini which can be found at sourceforge.net

For an example:

using Nini;
using Nini.Config;

namespace niniDemo{
   public class niniDemoClass{
       public bool LoadIni(){
            string configFileName = "demo.ini";
            IniConfigSource configSource = new IniConfigSource(configFileName);

            IConfig demoConfigSection = configSource.Configs["Demo"];
            string demoVal = demoConfigSection.Get("demoVal", string.Empty);
       }
   }

}

The above sample's 'demo.ini' file would be:

[Demo]
demoVal = foobar

If the value of demoVal is null or empty, it defaults to string.Empty.

青春如此纠结 2024-08-27 02:01:02

我编写了一个名为 DotNet.Config 的小型 .NET 配置库,它使用基于简单文本的属性文件受到 Java 的 .property 文件的启发。它包括一些易于加载的好功能。您可以在此处获取副本:

https://github.com/jknight/DotNet.Config

I've written a small .NET configuration library called DotNet.Config that uses simple text based property files inspired by Java's .property files. It includes some nice features for easy loading. You can grab a copy here:

https://github.com/jknight/DotNet.Config

澉约 2024-08-27 02:01:02

我无法找到使用 C# 读取属性文件的类似解决方案。我能够使用 c# 编写自己的代码,以获得与 java 中相同的结果。

以下是代码:

 // watchValue- Property attribute which you need to get the value;
 public string getProperty(string watchValue) 
    {
       // string propertiesfilename= @"readFile.properties";

        string[] lines = System.IO.File.ReadAllLines(propertiesfilename);
            for (int i = 0; i < lines.Length; i++)
            {
                string prop_title = Regex.Split(lines[i], "=")[0].Trim();
                if (prop_title == watchValue)
                    return Regex.Split(lines[i], "=")[1].Trim();
            }
            return null;
    }

我的想法

- 就我个人而言,我认为用户访问属性文件比访问 XML 文件要容易得多。

因此,如果您尝试外部化某些属性属性,最好使用属性文件而不是 XML。

I didnt able to find a similer solution for the read properties file by using c#. I was able to write a own code by using c# for get the same result as same as in java.

Follow is the code:

 // watchValue- Property attribute which you need to get the value;
 public string getProperty(string watchValue) 
    {
       // string propertiesfilename= @"readFile.properties";

        string[] lines = System.IO.File.ReadAllLines(propertiesfilename);
            for (int i = 0; i < lines.Length; i++)
            {
                string prop_title = Regex.Split(lines[i], "=")[0].Trim();
                if (prop_title == watchValue)
                    return Regex.Split(lines[i], "=")[1].Trim();
            }
            return null;
    }

My Idea-

Personally I believe that Properties file access is much more easy to user than accessing XML files.

So If you try to externalize some attribute property better to use Properties file than XML.

秋意浓 2024-08-27 02:01:02

我个人很喜欢在网上找到的这段代码。这是一种在属性文件中读/写的个性化方式。

public class Properties
{
    private Dictionary<String, String> list;

    private String filename;

    public Properties(String file)
    {
        reload(file);
    }

    public String get(String field, String defValue)
    {
        return (get(field) == null) ? (defValue) : (get(field));
    }
    public String get(String field)
    {
        return (list.ContainsKey(field))?(list[field]):(null);
    }

    public void set(String field, Object value)
    {
        field = this.trimUnwantedChars(field);
        value = this.trimUnwantedChars(value);

        if (!list.ContainsKey(field))
            list.Add(field, value.ToString());
        else
            list[field] = value.ToString();
    }

    public string trimUnwantedChars(string toTrim)
    {
        toTrim = toTrim.Replace(";", string.Empty);
        toTrim = toTrim.Replace("#", string.Empty);
        toTrim = toTrim.Replace("'", string.Empty);
        toTrim = toTrim.Replace("=", string.Empty);
        return toTrim;
    }

    public void Save()
    {
        Save(this.filename);
    }

    public void Save(String filename)
    {
        this.filename = filename;

        if (!System.IO.File.Exists(filename))
            System.IO.File.Create(filename);

        System.IO.StreamWriter file = new System.IO.StreamWriter(filename);

        foreach(String prop in list.Keys.ToArray())
            if (!String.IsNullOrWhiteSpace(list[prop]))
                file.WriteLine(prop + "=" + list[prop]);

        file.Close();
    }

    public void reload()
    {
        reload(this.filename);
    }

    public void reload(String filename)
    {
        this.filename = filename;
        list = new Dictionary<String, String>();

        if (System.IO.File.Exists(filename))
            loadFromFile(filename);
        else
            System.IO.File.Create(filename);
    }

    private void loadFromFile(String file)
    {
        foreach (String line in System.IO.File.ReadAllLines(file))
        {
            if ((!String.IsNullOrEmpty(line)) &&
                (!line.StartsWith(";")) &&
                (!line.StartsWith("#")) &&
                (!line.StartsWith("'")) &&
                (line.Contains('=')))
            {
                int index = line.IndexOf('=');
                String key = line.Substring(0, index).Trim();
                String value = line.Substring(index + 1).Trim();

                if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
                    (value.StartsWith("'") && value.EndsWith("'")))
                {
                    value = value.Substring(1, value.Length - 2);
                }

                try
                {
                    //ignore duplicates
                    list.Add(key, value);
                }
                catch { }
            }
        }
    }
}

使用示例:

//load
Properties config = new Properties(fileConfig);
//get value whith default value
com_port.Text = config.get("com_port", "1");
//set value
config.set("com_port", com_port.Text);
//save
config.Save()

I personally like this piece of code I found on the Web. It is a personnalized way to read/write in a properties file.

public class Properties
{
    private Dictionary<String, String> list;

    private String filename;

    public Properties(String file)
    {
        reload(file);
    }

    public String get(String field, String defValue)
    {
        return (get(field) == null) ? (defValue) : (get(field));
    }
    public String get(String field)
    {
        return (list.ContainsKey(field))?(list[field]):(null);
    }

    public void set(String field, Object value)
    {
        field = this.trimUnwantedChars(field);
        value = this.trimUnwantedChars(value);

        if (!list.ContainsKey(field))
            list.Add(field, value.ToString());
        else
            list[field] = value.ToString();
    }

    public string trimUnwantedChars(string toTrim)
    {
        toTrim = toTrim.Replace(";", string.Empty);
        toTrim = toTrim.Replace("#", string.Empty);
        toTrim = toTrim.Replace("'", string.Empty);
        toTrim = toTrim.Replace("=", string.Empty);
        return toTrim;
    }

    public void Save()
    {
        Save(this.filename);
    }

    public void Save(String filename)
    {
        this.filename = filename;

        if (!System.IO.File.Exists(filename))
            System.IO.File.Create(filename);

        System.IO.StreamWriter file = new System.IO.StreamWriter(filename);

        foreach(String prop in list.Keys.ToArray())
            if (!String.IsNullOrWhiteSpace(list[prop]))
                file.WriteLine(prop + "=" + list[prop]);

        file.Close();
    }

    public void reload()
    {
        reload(this.filename);
    }

    public void reload(String filename)
    {
        this.filename = filename;
        list = new Dictionary<String, String>();

        if (System.IO.File.Exists(filename))
            loadFromFile(filename);
        else
            System.IO.File.Create(filename);
    }

    private void loadFromFile(String file)
    {
        foreach (String line in System.IO.File.ReadAllLines(file))
        {
            if ((!String.IsNullOrEmpty(line)) &&
                (!line.StartsWith(";")) &&
                (!line.StartsWith("#")) &&
                (!line.StartsWith("'")) &&
                (line.Contains('=')))
            {
                int index = line.IndexOf('=');
                String key = line.Substring(0, index).Trim();
                String value = line.Substring(index + 1).Trim();

                if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
                    (value.StartsWith("'") && value.EndsWith("'")))
                {
                    value = value.Substring(1, value.Length - 2);
                }

                try
                {
                    //ignore duplicates
                    list.Add(key, value);
                }
                catch { }
            }
        }
    }
}

Example of usage:

//load
Properties config = new Properties(fileConfig);
//get value whith default value
com_port.Text = config.get("com_port", "1");
//set value
config.set("com_port", com_port.Text);
//save
config.Save()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文