Global access, XML File (Setting file) values

I use a custom XML to save my application setting (I am not interested in setting file or config file). I would like to read that settings and keep it to use it in other classes whenever necessary. What is the best way? Using a static class or any other ways?

Answers


I would say having a static class will do the job, I would just suggest paying attention to:

  • having static constructor, where the xml file will be parsed and values read and assigned into corresponding fields.
  • having default values, that will be assigned, if some data (or worst case whole xml file) will be missing
  • using public static auto-properties, which will only have getters. Hide your private fields.

EDIT

Reading the XML file from static constructor of static class:

public static class MyStaticClass
{
    //this is where we store the xml file line after line
    private static List<string> _xmlLines;

    //this is the class' static constructor
    //this code will be the first to run (you do not have to call it, it's automated)
    static MyStaticClass()
    {
        _xmlLines = new List<string>();

        using (System.IO.StreamReader xml = new System.IO.StreamReader("yourFile.xml"))
            {
                string line = null;
                while ((line = xml.ReadLine()) != null)
                {
                    _xmlLines.Add(line);
                }
            }
            //remember to catch your exceptions here
    }

    //this is the get-only auto property
    public static List<string> XmlLines
    {
        get
        {
            return _xmlLines;
        }
    }
}

Note: This is not production ready code, the types and logic of e.g. parsing the file are up to you, but I hope for demonstrative purposes, the code should be okay. If there is anything unclear, feel free to ask (but remember that the more info you provide, the more accurate the answers can be).


Need Your Help

Xcode 5: about 64-bits architecture and backwards compatibility

ios ios5 ios7 64bit xcode5

I've developed an iOS app whose Deployment Target needs to be 5.0, so the target's Build Settings > Architectures > Architectures value has to be the standard without the 64-bit one (XCode complains