27

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.

informatik01
  • 16,038
  • 10
  • 74
  • 104
Electrons_Ahoy
  • 36,743
  • 36
  • 104
  • 127
  • There is a dup: http://stackoverflow.com/questions/485659/can-c-load-and-parse-a-properties-file-equivilant-to-java-properties-class – skaffman Jan 30 '10 at 22:32
  • These seem similar: http://stackoverflow.com/questions/485659/can-c-load-and-parse-a-properties-file-equivilant-to-java-properties-class http://stackoverflow.com/questions/217902/reading-writing-ini-file-in-c – mtmk Jan 30 '10 at 22:38
  • Depending on the authors intent, this may not be a dup. (though it would seem as one given the author isn't keen on XML) Andrew Hare has already provided the only possible answer if this isn't a dup. – Jason D Jan 30 '10 at 22:38
  • Well, yeah - I wasn't looking for a way to read .properties specifically; I just wanted to know what the .net equivalent was. (and was hoping for a non-xml based solution, but then again, this is .net we're talking about.) I'll clean up the text in the question to make that a little more clear. – Electrons_Ahoy Jan 31 '10 at 01:22
  • Would something like [JSON.net](http://www.newtonsoft.com/json) fill the bill? – radarbob Jan 28 '17 at 01:29

6 Answers6

17

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

adrianbanks
  • 81,306
  • 22
  • 176
  • 206
8

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

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
  • 4
    Aren't config files meant for just application config data? I really just want an easy way to pull some strings out of a text file. I don't want the framework to think I'm trying to configure something. :) – Electrons_Ahoy Jan 31 '10 at 01:29
5

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.

t0mm13b
  • 34,087
  • 8
  • 78
  • 110
4

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

Jeffrey Knight
  • 5,888
  • 7
  • 39
  • 49
2

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.

Milinda Bandara
  • 542
  • 8
  • 23
  • 1
    You do not want to look for =s only, but also : and (spacebar), according to https://en.wikipedia.org/wiki/.properties – Happypig375 Jul 24 '16 at 04:22
0

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