Question

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.

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.

(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.)

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.

Was it helpful?

Solution

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.

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).

OTHER TIPS

The .NET way is to use a configuration file. The .NET framework even offers an API for working with them.

There is a third party component called nini which can be found at 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]
demoVal = foobar

If the value of demoVal is null or empty, it defaults to string.Empty.

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.

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.

So If you try to externalize some attribute property better to use Properties file than XML.

I've written a small .NET configuration library called DotNet.Config that 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:

https://github.com/jknight/DotNet.Config

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()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top