1

我需要读取/写入与任何 exe 无关的配置文件。我正在尝试这个:

        var appConfiguration = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap() { ExeConfigFilename = "SlamDunkSuper.config" }, ConfigurationUserLevel.None);
        if(appConfiguration == null) {

           //Configuration file not found, so throw an exception
           //TODO: thow an exception here
        } else {

           //Have Configuration, so work on the contents
           var fileEnvironment = appConfiguration.GetSection("fileEnvironment");
        }

不会抛出异常,但 fileEnvironment 始终为 null。这是文件内容:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <configSections>
      <section name="fileEnvironment" type="System.Configuration.NameValueSectionHandler"/>
   </configSections>

   <fileEnvironment>
      <add key="DxStudioLocation" value="123456"/>
   </fileEnvironment>
</configuration>

请有人带我走出荒野。在获得该部分的内容后,我也不知道如何编写或更改 NameValueCollection 中的条目。谢谢

4

2 回答 2

0

您可以通过一些小的调整来全球化AppSettingsSection :

<section name="fileEnvironment" type="System.Configuration.AppSettingsSection"/>

消费:

        var appConfiguration = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap() { ExeConfigFilename = "SlamDunkSuper.config" }, ConfigurationUserLevel.None);

        if (!appConfiguration.HasFile) // no need to null check, ConfigurationManager.OpenMappedExeConfiguration will always return an object or throw ArgumentException
        {
            //Configuration file not found, so throw an exception
        }
        else
        {
            var section = appConfiguration.GetSection("fileEnvironment") as AppSettingsSection;
            if (section != null)
            {
                var dxStudioLocation = section.Settings["DxStudioLocation"].Value;
            }
        }
于 2012-01-21T23:02:41.127 回答
-2

在 .net 中,配置文件由正在运行的 exe 文件选择,因此,如果您有 5 个项目(4 个 dll 和一个 exe),并且每个项目都有不同的配置文件,那么当您从 exe 文件运行应用程序时,dll 是被他加载会认为exe的配置文件是他们的配置文件。

换句话说,要读取 dll 项目的配置文件,您需要使用他的路径显式打开它。

希望能帮助到你

于 2012-01-21T09:50:45.630 回答