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

Is it possible to detect if a script is being loaded as a RequireJS module?

javascript requirejs amd

I'm researching whether there is a way to detect, for sure, whether a given script is currently being loaded by RequireJS. An answer for AMD modules in general would be even better, but my use cas...

Android VBO / IBO not working correctly

android opengl-es-2.0

Currently I am working on a 3D Game Engine for Android. The Project is just at the beginning, but there is a problem I cant' solve.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.