简体   繁体   中英

How can I get appSetting values from a specific config file

I'm trying to inject a mock of a configuration reader defined as

public interface IConfigurationReader
{
    string GetConfigSetting(string settingName);
}

and in the implementation looks like:

    private class MyConfig : cherry.Framework.IConfigurationReader
    {
        public string GetConfigSetting(string settingName)
        {
            return ConfigurationManager.AppSettings[settingName];
        }
    }

The problem is of course this requires me to have an app.config file in this project. Ideally I want to do something like:

return Foo("c:\temp\someconfig.config\",settingName);

Is there a built-in method that will take a file name and return the desired setting?

XML to linq was my friend:

    private class MyConfig : cherry.Framework.IConfigurationReader
    {
        private String ConfigFile { get; set; }  

        public MyConfig(String configFile)
        {
            ConfigFile = configFile;
        }
        public string GetConfigSetting(string settingName)
        {
            var setting  = XDocument.Load(ConfigFile).Descendants("add").Select(s => new
            {
                AppKey = s.Attribute("key"),
                AppValue = s.Attribute("value")
            }).FirstOrDefault(x => x.AppKey.Value == settingName);
            if (setting == null)
            {
                throw new Exception("key not found!");
            }
            else
                return setting.AppValue.Value;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM