C# - 如何确定映射的 EXE 配置文件中是否存在配置节



我有一个C#项目,它正在读取一个名为test.config的独立配置文件。这是一个独立于典型App.config的文件。

我正在尝试确定test.config文件是否包含代码TestProperty的可选属性。我尝试使用TestProperty.ElementInformation.IsPresent但这总是导致 FLASE 的值,即使部分元素实际存在。

class Program
{
    static void Main(string[] args)
    {
        string filePath = @"C:UsersusernameDesktopTestProjectConfigTestAppTest.Config";
        ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(filePath);
        fileMap.ExeConfigFilename = Path.GetFileName(filePath);
        Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
        TestConfigSection section = config.GetSection("TestConfigSection") as TestConfigSection;
        bool isPresent = section.TestProperty.ElementInformation.IsPresent; // Why is this always false?
    }
}

test.config文件如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name ="TestConfigSection" type ="ConfigTestApp.TestConfigSection, ConfigTestApp"/>
  </configSections>
  <TestConfigSection>
    <TestProperty testvalue="testing 123" />
  </TestConfigSection>
</configuration>

支持类是:

public class TestConfigSection : ConfigurationSection
{
    [ConfigurationProperty("TestProperty", IsRequired = true)]
    public TestConfigElement TestProperty
    {
        get
        {
            return base["TestProperty"] as TestConfigElement;
        }
    }
}
public class TestConfigElement : ConfigurationElement
{
    [ConfigurationProperty("testvalue", IsKey = true, IsRequired = true)]
    public string TestValue
    {
        get { return base["testvalue"] as string; }
        set { base["testvalue"] = value; }
    }
}

如果我将该部分移动到 App.config 并使用 ConfigurationManager.GetSection("TestConfigSection") ,IsPresent 似乎工作正常,但我需要它从一个单独的文件 (test.config( 工作。

有没有办法让TestProperty.ElementInformation工作或任何其他方法来确定 test.config 文件是否包含 TestProperty 属性?

也许这是你的问题:

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(filePath);
fileMap.ExeConfigFilename = Path.GetFileName(filePath);

ExeConfigFilename不应该是这样的文件的完整路径吗?

fileMap.ExeConfigFilename = filePath;

如果这不是问题所在,我最近不得不做一些像你正在做的事情,这就是我所做的(使用你的示例数据(。

string filePath = @"C:UsersusernameDesktopTestProjectConfigTestAppTest.Config";
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
AppSettingsSection section = (AppSettingsSection) config.GetSection("TestConfigSection");
if ( section != null )
{
  string testValue = section .Settings["TestProperty"].Value;
}

在我的配置文件中,我使用了这种类型的格式:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <TestConfigSection file="">
    <clear />
    <add key="TestProperty" value="testing 123" />
  </TestConfigSection>
</configuration>

最新更新