Writing to Config file WITHOUT "System.Configuration" (Windows CE)

Rédigé par Sozezzo - - Aucun commentaire

A config file for a .NET application is a text file that has a name of myapplication.exe.config.

The Windows CE does not make things easy for you!
It allows you to add a file named “App.config” to your project and it will copy it to the appropriate bin directory and rename it to myapplication.exe.config, but you cannot access it.

App.condig is nothing more than XML. Here's my version to access config file by Windows CE Application :

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;

namespace SmartDevice.Utils
{
    public static class AppSettings
    {
        #region Public Static Members

        public static NameValueCollection Settings = new NameValueCollection();
        public static bool _loaded = false;

        #endregion Public Static Members

        #region Private Static Members

        //static string configFile = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase), "App.config");
        static string configFile = string.Format("{0}.{1}", Assembly.GetExecutingAssembly().GetName().CodeBase, "config");
        static bool _isAppConfigExist = false;

        #endregion Private Static Members

        #region Static Constructors

        static AppSettings()
        {
            if (File.Exists(configFile))
            {
                isAppConfigExist = true;
                Load();
            }
            else
            {
                isAppConfigExist = false;
            }
        }

        #endregion Static Constructors

        #region Public Static Properties

        public static bool isAppConfigExist
        {
            get
            {
                return _isAppConfigExist;
            }
            private set
            {
                _isAppConfigExist = value;
            }
        }

        #endregion Public Static Properties

        #region Public Static Methods

        public static string GetFile()
        {
            StreamReader streamReader = System.IO.File.OpenText(configFile);
            string ret = streamReader.ReadToEnd();
            streamReader.Close();
            return ret;
        }

        public static string GetValue(string key, string default_value)
        {
            if (!_loaded) Load();
            return isKeyOK(key) ? Settings.Get(key) : default_value;
        }

        public static void Load()
        {
            if (!File.Exists(configFile))
            {
                throw new FileNotFoundException(string.Format("Application configuration file '{0}' not found.", configFile));
            }

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(configFile);
            XmlNodeList nodeList = xmlDocument.GetElementsByTagName("appSettings");
            Settings = new NameValueCollection();

            foreach (XmlNode node in nodeList)
            {
                foreach (XmlNode key in node.ChildNodes)
                {
                    Settings.Add(key.Attributes["key"].Value, key.Attributes["value"].Value);
                }
            }
            _loaded = true;
        }

        public static void Save()
        {
            System.Text.StringBuilder sb = new StringBuilder();
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n\r\n<configuration><appSettings>\r\n</appSettings>\r\n</configuration>");
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(sb.ToString());

            XmlNode root = xmlDocument.DocumentElement.ChildNodes[0];

            for (int i = 0; i < Settings.Count; ++i)
            {
                XmlElement addElement = xmlDocument.CreateElement("add");
                string key = Settings.GetKey(i);
                string value = Settings.GetValues(i)[0].ToString();
                addElement.SetAttribute("key", key);
                addElement.SetAttribute("value", value);
                root.AppendChild(addElement);
            }
            xmlDocument.Save(configFile);
        }

        public static void SetValue(string key, string newValue)
        {
            if (isKeyOK(key))
                Settings.Set(key, newValue);
            else
                Settings.Add(key, newValue);
        }

        #endregion Public Static Methods

        #region Private Static Methods

        private static bool isKeyOK(string key)
        {
            if (!Settings.HasKeys()) return false;
            key = key.ToLower();
            if (Settings.AllKeys.Count(p => p.ToLower() == key) == 0) return false;
            if (Settings.AllKeys.Count(p => p.ToLower() == key) != 1)
            {
                //string configFile = Path.Combine(appPath, "App.config");
                throw new FileNotFoundException(string.Format("Application configuration file '{0}' had an error. Double key: ", configFile, key));
            }
            return true;
        }

        #endregion Private Static Methods
    }
}

 

Source:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/d68a872e-14bc-414a-82c4-d1035a11b4a8/how-do-i-updateinsertremove-the-config-file-during-runtime?forum=csharpgeneral
http://stackoverflow.com/questions/20614189/create-app-config-file-if-doesnt-exist-c-sharp
http://ryanfarley.com/blog/archive/2004/07/13/879.aspx
http://www.codeproject.com/Articles/12589/Modifying-Configuration-Settings-at-Runtime
http://stackoverflow.com/questions/5468342/how-to-modify-my-app-exe-config-keys-at-runtime
http://stackoverflow.com/questions/6402596/xml-string-to-xml-document
http://www.tutorialized.com/tutorial/Add-remove-elements-to-from-an-XML-Document-using-C/45101
https://msdn.microsoft.com/en-us/library/system.xml.xmldocument.createcomment%28v=vs.110%29.aspx

 

Les commentaires sont fermés.