How do I retrieve ApplicationSettings from a loaded App.config file?

前端 未结 3 1812
故里飘歌
故里飘歌 2020-12-08 22:53

Is it possible to access the values from the applicationSettings section of a loaded app.config file?

I have found an example How do I

3条回答
  •  旧时难觅i
    2020-12-08 23:37

    You could load the config file into XmlDocument and retrive the applicationSettings from the dom object . Here is example I found to load the config file into dom object :

    //retrive the current assembly directory
    private static string AssemblyDirectory()
    {
            string codeBase = Assembly.GetExecutingAssembly().CodeBase;
            UriBuilder uri = new UriBuilder(codeBase);
            string path = Uri.UnescapeDataString(uri.Path);
            return Path.GetDirectoryName(path);
    }
    
    
    
    //return the value from aplicationSetting according to the given key
    //appSettingSection is the your configuration section as declare in your web.config
    public static string GetApplicationSettingValue(string appSettingSection,string key)
    {
       //get web.config path
       string configPath  = new System.IO.DirectoryInfo(AssemblyDirectory()).Parent.FullName + "\\web.config";
    
        System.IO.FileInfo FileInfo = new System.IO.FileInfo(configPath);
        if (!FileInfo.Exists)
        {
            throw new Exception("Missing config file");
        }
    
        //load config file into xml document
        var XmlConfig = new System.Xml.XmlDocument();
        XmlConfig.Load(FileInfo.FullName);
    
    
         //override xml document and return the value of the key under applicationSettings
         foreach (System.Xml.XmlNode node in XmlConfig["configuration"]  ["applicationSettings"]appSettingSection])
         {
                        if (node.Name == "setting")
                        {
                            if (node.Attributes.GetNamedItem("name").Value == key)
                            {
                                return node.FirstChild.InnerXml.ToString();
                            }
                       }
         }
       return "";
    }
    

提交回复
热议问题