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

Is there an easy way in C # to read a properties file that has each property on its own line, followed by an equal sign and value, for example the following:

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

In Java, the Properties class handles this analysis 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 upload a file in C # and parse every line, but is there a built-in way to easily get a property without having to parse the key name and equal sign? The C # information that I found seems to always favor XML, but it is an existing file that I do not control, and I would prefer to save it in the existing format, since it will take more time to force another command to change it to XML than analysis of an existing file.

+41
c # file-io configuration load
Jan 27 '09 at 22:36
source share
11 answers

There is no built-in support for this.

You must create 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.

+33
Jan 27 '09 at 22:49
source share

Most Java.properties files can be separated by assuming that "=" is a separator - but the format is much more complex than this and allows you to embed spaces, equalities, newlines, and any Unicode characters either in the property name or value.

I needed to load some Java properties for a C # application, so I used JavaProperties.cs to read and write formatted .properties files correctly using the same approach as the Java version - you can find it at http: // www. kajabity.com/index.php/2009/06/loading-java-properties-files-in-csharp/ .

There you will find a zip file containing the C # source for the class and some sample properties files with which I tested it.

Enjoy it!

+17
Jun 07 '09 at 17:24
source share

Final grade. Thanks @eXXL .

 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) { if (!list.ContainsKey(field)) list.Add(field, value.ToString()); else list[field] = value.ToString(); } 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 dublicates list.Add(key, value); } catch { } } } } } 

Using an example:

 //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() 
+15
Oct 08 2018-11-11T00:
source share

I wrote a method that allows you to create emty, outcommenting and quoting lines inside a file.

Examples:

var1 = "value1"
var2 = 'value2'

'var3 = outcommented
; var4 = outcommented, too

Here's the method:

 public static IDictionary ReadDictionaryFile(string fileName) { Dictionary<string, string> dictionary = new Dictionary<string, string>(); foreach (string line in File.ReadAllLines(fileName)) { 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); } dictionary.Add(key, value); } } return dictionary; } 
+6
May 14, '09 at 10:53
source share

Yes, there are no built-in classes for this that I know of.

But this should not be a problem, if so? It looks simple enough to parse by simply storing the result of Stream.ReadToEnd() in a line, breaking based on new lines, and then breaking each entry into a = character. What remains for you is a bunch of key pairs that you can easily insert into your dictionary.

Here is an example that might work for you:

 public static Dictionary<string, string> GetProperties(string path) { string fileData = ""; using (StreamReader sr = new StreamReader(path)) { fileData = sr.ReadToEnd().Replace("\r", ""); } Dictionary<string, string> Properties = new Dictionary<string, string>(); string[] kvp; string[] records = fileData.Split("\n".ToCharArray()); foreach (string record in records) { kvp = record.Split("=".ToCharArray()); Properties.Add(kvp[0], kvp[1]); } return Properties; } 

Here is an example of how to use it:

 Dictionary<string,string> Properties = GetProperties("data.txt"); Console.WriteLine("Hello: " + Properties["Hello"]); Console.ReadKey(); 
+2
Jan 27 '09 at 10:50
source share

C # usually uses xml-based configuration files, not a * .ini-type file, as you said, so there is nothing to handle this. However, google returns a number of promising results .

+1
Jan 27 '09 at 22:45
source share

I do not know any built-in way to do this. However, this would be easy enough to do, as the only delimiters you should worry about are the newline and the equal sign.

It would be very easy to write a procedure that returns a NameValueCollection or IDictionary, given the contents of the file.

+1
Jan 27 '09 at 22:48
source share

You can also use C # auto syntax syntax with default values ​​and a restrictive set. The advantage here is that then you can have a data type of any type in your file "file" (now actually a class). Another advantage is that you can use the C # property syntax to call properties. However, you just need a couple of lines for each property (one in the property declaration and one in the constructor) to make this work.

 using System; namespace ReportTester { class TestProperties { internal String ReportServerUrl { get; private set; } internal TestProperties() { ReportServerUrl = "http://myhost/ReportServer/ReportExecution2005.asmx?wsdl"; } } } 
+1
Sep 12 '11 at 19:56
source share

The real answer is no (at least not by itself). You can write your own code to do this.

+1
Feb 09 '12 at 22:00
source share

I understand that this is not exactly what you are asking, but just in case:

If you want to load the actual Java properties file, you will need to encode it. Java docs show that encoding is an ISO 8859-1 that contains some escape sequences that you may misinterpret. For example, check out this SO answer to find out what is needed to convert UTF-8 to ISO 8859-1 (and vice versa)

When we needed to do this, we discovered the open-source PropertyFile.cs and made a few changes to support escape sequences. This class is good for read / write scripts. You will need the PropertyFileIterator.cs class.

Even if you are not loading the true Java properties, make sure your prop file can express all the characters you need to keep (at least UTF-8)

0
Mar 16 '10 at 20:07
source share

There is an exact solution to what you want. please find the article here

his code has a bunch of strengths regarding performance.

  • The application does not load a text file in each request. This loads a text file only once into memory. For a subsequent request, it returns the value directly from memory. This is much more efficient if your text file contains thousands or more key-value pairs.
  • Any change to the text file does not require a restart of the application. The file system watcher was used to track file status. If it changes, it fires an event and loads new changes according to memory so that you can change the text file in one application / text editor and see the changed effect on the Internet application.
  • You can not only use it in a web application, but also use it in any desktop application.

Thank. Have a nice day.

0
Jun 15 '15 at 6:36
source share



All Articles