【问题标题】:How to open a file formatted as a .NET config file to get a System.Configuration.Configuration object如何打开格式化为 .NET 配置文件的文件以获取 System.Configuration.Configuration 对象
【发布时间】:2014-04-07 21:03:40
【问题描述】:

我在一个 ASP.NET 应用程序中,我想打开一个文件,其格式类似于 web.config 或您可以将其链接到的配置文件之一(appSettings、页面等)并获取 appSettings

Dim filePath As String = HostingEnvironment.MapPath("~/developer.config")
If (File.Exists(filePath)) Then
   Dim map As New WebConfigurationFileMap()
   map.MachineConfigFilename = filePath
   Dim config As System.Configuration.Configuration = System.Web.Configuration.WebConfigurationManager.OpenMappedWebConfiguration(map, "/")
   Dim developerAppSettings As AppSettingsSection = config.AppSettings
   Return developerAppSettings
Else
   Return Nothing
End If

我希望将 developerAppSettings 设置为我的 developer.config 文件的 appSettings 部分,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<appSettings>
    <add key="CustomerLogosFolder" value="C:\code\ExactBidTFS\RIMS\Development\CustomerLogos" />
</appSettings>

显然,我没有正确使用 OpenMappedWebConfiguration(),因为它给了我一个 ArgumentOutOfRange 异常(它似乎是第二个“/”参数)。

这甚至可能吗?我也尝试过 OpenWebConfiguration() ,但在这种情况下文件路径参数的用途似乎有些混乱。我的实验表明文件路径只是一个包含web.config的虚拟目录,而不是指定我自己的developer.config文件。

【问题讨论】:

    标签: asp.net .net configuration


    【解决方案1】:

    我在尝试寻找从控制台应用程序打开 Web 应用程序配置文件的方法时看到了这个问题。我还看到了帮助我的帖子here

    我知道这是一个老问题,但我想我不妨在这里发布我的解决方案。

    我写了以下 sn-p,它对我有用:

    Dim map As New ExeConfigurationFileMap()
    Dim filePath As String = "c:\temp\developer.config"
    map.ExeConfigFilename = filePath
    Dim configFile As Configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None)
    If configFile IsNot Nothing Then
      Dim myAppSection As AppSettingsSection = TryCast(configFile.GetSection("appSettings"), AppSettingsSection)
      Debug.Print(myAppSection.Settings("CustomerLogosFolder").Value)
    End If
    

    我还对 xml 进行了如下修改,使其与其他配置文件相似:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
        <appSettings>
            <add key="CustomerLogosFolder" value="C:\code\ExactBidTFS\RIMS\Development\CustomerLogos" />
        </appSettings>
    </configuration>
    

    在执行结束时,我的即时窗口中出现“C:\code\ExactBidTFS\RIMS\Development\CustomerLogos”

    【讨论】:

      猜你喜欢
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      相关资源
      最近更新 更多