【问题标题】:Is there an easy way to read the appsettings of a web.config file just by using it's path?有没有一种简单的方法可以通过使用它的路径来读取 web.config 文件的 appsettings?
【发布时间】:2011-10-22 15:31:41
【问题描述】:

这对我来说似乎很简单,但我似乎无法找到正确的谷歌查询来帮助我..

我有 一些 web.config 文件位于 C:\temp 中,并且希望能够使用像 myWebConfig.AppSettings["myParam"] 这样的东西。 这个可以吗?

我尝试使用ConfigurationManager.OpenMappedMachineConfigurationConfigurationManager.OpenExeConfigurationWebConfigurationManager.OpenWebConfigurationWebConfigurationManager.OpenMappedWebConfiguration

也许我只是没有以正确的方式使用它们或者..?

[更新]
tvanfossen 写的是正确的。我没有编辑权限,所以我将在这里编写我最后使用的代码。

/* Method based on what I found on http://stackoverflow.com/questions/4339167/how-to-read-a-configuration-section-from-xml-in-a-database/4844365#4844365
 * and tvanvossens answer.
 * There's probably room for improvement, but it does what I need now.
 */
private static T GetSection<T>(string pathToWebConfigFile, string configNode) where T : ConfigurationSection, new()
{
    var doc = XDocument.Load(pathToWebConfigFile);
    var element = doc.Element("configuration").Element(configNode);
    var reader = element.CreateReader();
    var settingsSection = new T();
    settingsSection.GetType().GetMethod("DeserializeSection", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(settingsSection, new object[] { reader });
    return settingsSection;
}

用法示例:

var settingsSection = GetSection<AppSettingsSection>(pathToWebConfigFile, "appSettings");
var connectionStringSection = GetSection<ConnectionStringsSection>(pathToWebConfigFile, "connectionStrings");

【问题讨论】:

    标签: .net web-config configurationmanager


    【解决方案1】:

    取决于您所说的“简单”是什么意思。我认为可以使用反射来完成,但不会特别灵活。

    首先,您需要以 XML 格式打开文档并找到 appSettings 部分。然后,您将为该部分创建一个 XmlReader。然后,创建一个 AppSettingsSection 并使用反射调用 DeserializeSection() 方法,并将阅读器作为参数。您可能会使用 Reflector 来查看 ConfigurationManager 是如何做到这一点的,因为可能需要调用 AppSettingsSection 上的其他方法来完成该部分的加载。

    完全未经测试的示例...

     XDocument doc = XDocument.Load(@"c:\temp\web.config");
     var appSettingsElement = doc.Elements("appSettings").First();
     var reader = appSettingsElement.CreateReader();
     var settings = new AppSettingsSection();
     var method = typeof(AppSettingsSection).GetMethod("DeserializeSection",
                                                       BindingFlags.NonPublic,
                                                       null,
                                                       null,
                                                       new[] { typeof(XmlReader) },
                                                       null );
     method.Invoke( settings, new [] { reader } );
    
     var value = settings["myParam"];
    

    【讨论】:

      【解决方案2】:

      假设您的变量是 "YourVariable"

      以下代码行,返回文件路径。

      HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["YourVariable"])
      

      要只访问 web.config 的值,那么这样写。

      System.Configuration.ConfigurationManager.AppSettings["YourVariable"]
      

      在您的项目中,您应该插入 System.configuration 作为 References

      【讨论】:

      • 我认为你理解我的问题是错误的 :) 我正在尝试读取 web.config 文件,而不是正在运行的 Web 应用程序的“默认”web.config 文件中的参数..跨度>
      【解决方案3】:

      底线,是 --- 否。appSettings 配置部分是一个 xml 元素,其内容在整个宿主应用程序中分层配置结构,可以包括许多 个单独的文件。 appSettings 部分所在的文件(或文件*)由配置系统中的其他设置决定。因此,您无法仅通过文件 pr 路径规范来进行设置,您必须通过内置的 .Net 配置系统方法。

      • 基于配置系统中的其他设置,一个部分可以放在另一个文件中,或者一个部分中的个别设置可以位于不同文件中,位于配置系统层次结构的不同级别)

      【讨论】:

        【解决方案4】:

        我看到你已经尝试过WebConfigurationManager.OpenWebConfiguration(...) - 你错过了config.AppSettings吗?

        // Resolved from the application root with "~"
        // "~/MySubfolder/With/SpecialConfig/" works; values are read hierarchically
        var relativePath = "~/";
        
        var config = WebConfigurationManager.OpenWebConfiguration(relativePath);
        
        var myParam = config.AppSettings.Settings["myParam"].Value;
        
        // You can use it to save settings too
        config.AppSettings.Settings["myParam"].Value = "my new param value";
        
        config.Save(ConfigurationSaveMode.Modified);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-12-17
          • 2015-05-12
          • 1970-01-01
          • 2011-06-03
          • 1970-01-01
          • 2012-01-05
          • 2022-07-13
          • 2019-07-02
          相关资源
          最近更新 更多