Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can .NET load and parse a properties file equivalent to Java Properties class?

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 

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

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.

like image 255
Tai Squared Avatar asked Jan 27 '09 22:01

Tai Squared


People also ask

What type of file is the properties file in Java?

properties is a file extension for files mainly used in Java-related technologies to store the configurable parameters of an application. They can also be used for storing strings for Internationalization and localization; these are known as Property Resource Bundles.

Do Java classes have properties?

Properties are configuration values managed as key/value pairs. In each pair, the key and value are both String values. The key identifies, and is used to retrieve, the value, much as a variable name is used to retrieve the variable's value.


1 Answers

No there is no built-in support for this.

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

Edit: Updated to reflect Paul's comment.

like image 140
Jesper Palm Avatar answered Sep 22 '22 11:09

Jesper Palm