可.NET加载和分析属性文件等同于Java属性类? [英] Can .NET load and parse a properties file equivalent to Java Properties class?

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

问题描述

有没有在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中,属性类可以轻松地处理这个解析:

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,但是这是一个已经存在的文件,我不控制,我会preFER以保持其现有的格式,因为它会需要更多的时间去另一支球队来改变它比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属性类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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