Web应用程序或Windows应用程序加载????。config

时间:2013-03-08 06:57:48

标签: c# asp.net .net

我有一个项目,其中一些类根据可在app.config或web.config中配置的参数进行操作。

项目/类在Web环境中与在Windows应用程序环境中交互一样多。问题是:如何检测它是什么类型的项目,知道我应该读取app.config还是web.config?

目前,我有两个加载数据的类,一个Web和一个Windows应用程序;我如何制作一个决定使用哪个?我必须修改我的代码以使用其中一个,这会影响我对公共类的维护。

我将这些类作为参考附加:

namespace MyAppSetting.Windows
{
    public class MyGetConfig
    {
        private static Assembly currentAssembly = Assembly.GetCallingAssembly();
        private static Configuration FileAppConfig = ConfigurationManager.OpenExeConfiguration(AppDomain.CurrentDomain.BaseDirectory + AppDomain.CurrentDomain.FriendlyName.Replace(".svhost", ""));
        private static AppSettingsSection App_Config = FileAppConfig.AppSettings;

        public static string getValue(string Key, string DefaultValue = "")
        {
            // If it's null it doesn't exist ... if it's not null and Update Default if it's blank And there is a default value, and the config is blank
            if (App_Config.Settings[Key] == null || App_Config.Settings[Key].Value == null || App_Config.Settings[Key].Value.Trim() == "")
                return DefaultValue;
            return App_Config.Settings[Key].Value;
        }
    }
}

namespace MyAppSetting.Web
{
    public class MyGetConfig
    {
        private static System.Collections.Specialized.NameValueCollection App_Config = System.Web.Configuration.WebConfigurationManager.AppSettings;

        public static string getValue(string Key, string DefaultValue = "")
        {
            // If it's null it doesn't exist ... if it's not null and Update Default if it's blank And there is a default value, and the config is blank
            if (App_Config[Key] == null || App_Config[Key].Trim() == "")
                return DefaultValue;
            else
                return App_Config[Key];
        }
    }
}

我的解决方案

我的最终解决方案是:

    #region Win App Resources 4 Read Configuration
    private static Configuration FileAppConfig = null;
    private static AppSettingsSection winApp_Config = null; 
    #endregion Win App Resources 4 Read Configuration

    #region WEB App Resources 4 Read Configuration
    private static System.Collections.Specialized.NameValueCollection webApp_Config = null;
    #endregion WEB App Resources 4 Read Configuration

    public static void Inicialize()
    {
        FileAppConfig = null;
        winApp_Config = null;
        webApp_Config = null;
        try
        {
            FileAppConfig = ConfigurationManager.OpenExeConfiguration(AppDomain.CurrentDomain.BaseDirectory + AppDomain.CurrentDomain.FriendlyName.Replace(".vshost", ""));
            winApp_Config = FileAppConfig.AppSettings;
            TipoDeApp = TipoApp.Win;
        }
        catch
        {
            try
            {
                webApp_Config = System.Web.Configuration.WebConfigurationManager.AppSettings;
                TipoDeApp = TipoApp.Web;
            }
            catch { TipoDeApp = TipoApp.Desconocido; }
        }
    }

接下来......通过XMLDocument阅读设置....(基于Read config file using XMl reader

    public static string getValueFromSection(string Key, string DefaultValue = "", string Section = "appSettings")
    {
        Section = Section.Trim() == "" ? "appSettings" : Section.Trim();
        try
        {
            var dic = new Dictionary<string, string>();

            if (AllwaysLoadFromConfigFile || FileAppConfig == null)
                Inicialize();

            // Idea original: https://stackoverflow.com/questions/3868179/read-config-file-using-xml-reader
            XmlDocument xdoc = new XmlDocument();

            if (TipoDeApp == TipoApp.Win)
                xdoc.Load(FileAppConfig.FilePath);
            else if (TipoDeApp == TipoApp.Web)
                xdoc.Load(AppDomain.CurrentDomain.BaseDirectory + "web.config");
            else
                return DefaultValue;

            foreach (XmlNode node in xdoc.SelectSingleNode("/configuration/" + Section))
                if ((node.NodeType != XmlNodeType.Comment) && node.Attributes["key"] != null && node.Attributes["key"].Value != null)
                    if (!dic.ContainsKey(node.Attributes["key"].Value.ToUpper()))
                        dic.Add(node.Attributes["key"].Value.ToUpper(), node.Attributes["value"] == null || node.Attributes["value"].Value == null ? "" : node.Attributes["value"].Value);
                    else
                        dic[node.Attributes["key"].Value.ToUpper()] = node.Attributes["value"] == null || node.Attributes["value"].Value == null ? "" : node.Attributes["value"].Value;

            if (dic != null && dic[Key.ToUpper()] != null)
                return dic[Key.ToUpper()];
        }
        catch { }
        return DefaultValue;
    }

最后,我的Config文件是:

  <configSections>
    <sectionGroup name="MySectionGroup">
      <section name="MySection1" type="System.Configuration.NameValueSectionHandler" />
      <section name="MySection1" type="System.Configuration.NameValueSectionHandler" />
    </sectionGroup>
  </configSections>

  <MySectionGroup>
    <MySection1>
      <add key="MyParam1" value="Hello" />
      <add key="MyParam2" value="3.1416" />
    </MySection1>
    <MySection2>
      <add key="MyParam1" value="true" />
      <add key="MyParam2" value="Another value" />
    </MySection2>
  </MySectionGroup>

1 个答案:

答案 0 :(得分:1)

您不必知道自己所处的项目类型。只需参考您的应用设置:

  ConfigurationManager.AppSettings["key"]

这在Web应用程序和桌面应用程序中的工作方式相同。