【发布时间】:2019-10-28 09:28:30
【问题描述】:
我有一个 C# 项目,它正在从名为 test.config 的独立配置文件中读取数据。这是与典型App.config 不同的单独 文件。
我正在尝试确定test.config 文件是否包含来自代码的可选属性TestProperty。我尝试使用TestProperty.ElementInformation.IsPresent,但这总是会导致 FLASE 的值,即使节元素实际上存在。
class Program
{
static void Main(string[] args)
{
string filePath = @"C:\Users\username\Desktop\TestProject\ConfigTestApp\Test.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 属性?
【问题讨论】:
-
我把它放在一个单元测试中,运行它,它对我有用。这让我想知道您是否可能有两个版本的文件。您可以查看
ElementInformation或SectionInformation以获取其他线索。这些东西曾经给我带来疯狂的悲伤。如果可以的话,您可能会发现从 JSON 文件或其他文件中读取数据会更容易,而且可以省去麻烦。 -
有趣,即使将 testconfig 部分放在单独的 xml 配置文件中,它也能正常工作? (即 - 不在 app.config 中,而是在名为 test.config 的单独文件中)
-
我使用了一个变量,这样我就有了 FileMap 的正确路径。这就是我讨厌这些课程的原因。如果他们不加载我想要一个例外 - 不让它看起来像它加载但值是默认值。我敢肯定他们有他们的理由,但这是一个巨大的痛苦。
标签: c# configuration configuration-files configurationmanager