.NET 是否具有与 Java 的 .properties 文件等效的文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2169712/
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
Does .NET have an equivalent to Java's .properties files?
提问by Electrons_Ahoy
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.
为了唤起大家的记忆,Java 有这些扩展名为“.properties”的文件,它们基本上是一个充满键值对的 ASCII 文本文件。该框架有一些非常简单的方法可以将该文件吸收到(本质上)一个花哨的哈希映射中。
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.
.NET 是否具有等效的功能?当然,我可以对 XML 文件做同样的事情,但如果您知道我的意思,我宁愿不必手动输入所有这些尖括号。此外,一种将所有数据在一行中吸收到内存中的数据结构的方法也很好。
(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.)
为了回答一些评论所暗示的问题,我不是在寻找一种在 .NET 下专门读取 java .properties 文件的方法,我正在寻找 .NET 世界中的功能等效项。(我希望它不是基于 XML 的,显然已经忘记了我们正在谈论的是 .NET。)
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.
而且,虽然配置文件很接近,但我需要存储一些任意字符串的方法,而不是应用程序配置信息,因此配置文件的重点和设计似乎偏离了基础。
采纳答案by adrianbanks
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.
您可以使用内置的设置文件(在 VS 中,添加一个新的“设置文件”)来实现与属性文件类似的功能——但它仍然是基于 XML 的。
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).
您可以使用自动生成的 Settings 类访问设置,甚至更新它们并将它们保存回配置文件 - 所有这些都无需编写任何样板代码。这些设置是强类型的,可以指定为“User”(保存到用户的 Application Data 文件夹)或“Application”(保存到与运行的 exe 相同的文件夹)。
回答by Andrew Hare
The .NET way is to use a configuration file. The .NET framework even offers an API for working with them.
.NET 方式是使用配置文件。.NET 框架甚至提供 了用于处理它们的 API。
回答by t0mm13b
There is a third party component called nini which can be found at sourceforge.net
有一个名为 nini 的第三方组件,可以在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.ini”文件将是:
[Demo] demoVal = foobar
If the value of demoValis null or empty, it defaults to string.Empty.
如果 的值为demoValnull 或为空,则默认为string.Empty。
回答by Milinda Bandara
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.
我无法使用 c# 找到读取属性文件的类似解决方案。我能够使用 c# 编写自己的代码以获得与 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.
我个人认为,用户访问属性文件比访问 XML 文件要容易得多。
So If you try to externalize some attribute property better to use Properties file than XML.
因此,如果您尝试将某些属性属性外部化,最好使用 Properties 文件而不是 XML。
回答by Jeffrey Knight
I've written a small .NET configuration library called DotNet.Configthat 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:
我编写了一个名为DotNet.Config的小型 .NET 配置库,它使用受 Java 的 .property 文件启发的基于简单文本的属性文件。它包括一些易于加载的不错的功能。您可以在此处获取副本:
回答by Mathieu Devost
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()

