.NET 可以加载和解析与 Java Properties 类等效的属性文件吗? [英] Can .NET load and parse a properties file equivalent to Java Properties class?

查看:26
本文介绍了.NET 可以加载和解析与 Java Properties 类等效的属性文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中是否有一种简单的方法来读取属性文件,该文件的每个属性都在单独的行上,后跟等号和值,例如以下内容:

Is there an easy way in C# to read a properties file that has each property on a separate line followed by an equals sign and the value, such as the following:

ServerName=prod-srv1
Port=8888
CustomProperty=Any value

在 Java 中,Properties 类可以轻松处理此解析:

In Java, the Properties class handles this parsing easily:

Properties myProperties=new Properties();
FileInputStream fis = new FileInputStream (new File("CustomProps.properties"));
myProperties.load(fis);
System.out.println(myProperties.getProperty("ServerName"));
System.out.println(myProperties.getProperty("CustomProperty"));

我可以轻松地在 C# 中加载文件并解析每一行,但是是否有一种内置的方法可以轻松获取属性而无需自己解析键名和等号?我发现的 C# 信息似乎总是支持 XML,但这是一个我无法控制的现有文件,我更愿意将其保留为现有格式,因为它需要更多时间让另一个团队将其更改为 XML而不是解析现有文件.

I can easily load the file in C# and parse each line, but is there a built in way to easily get a property without having to parse out the key name and equals sign myself? The C# information I have found seems to always favor XML, but this is an existing file that I don't control and I would prefer to keep it in the existing format as it will require more time to get another team to change it to XML than parsing the existing file.

推荐答案

不,没有对此的内置支持.

No there is no built-in support for this.

您必须制作自己的INIFileReader".也许像这样?

You have to make your own "INIFileReader". Maybe something like this?

var data = new Dictionary<string, string>();
foreach (var row in File.ReadAllLines(PATH_TO_FILE))
  data.Add(row.Split('=')[0], string.Join("=",row.Split('=').Skip(1).ToArray()));

Console.WriteLine(data["ServerName"]);

更新以反映保罗的评论.

Updated to reflect Paul's comment.

这篇关于.NET 可以加载和解析与 Java Properties 类等效的属性文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆