有没有办法获得基于任意xml的System.Configuration.Configuration实例?

我正在尝试对我编写的自定义ConfigurationSection进行unit testing,并且我想将一些任意配置XML加载到每个测试的System.Configuration.Configuration中(而不是将测试配置xml放在Tests.dll中)。配置文件。也就是说,我想做这样的事情:

Configuration testConfig = new Configuration("..."); MyCustomConfigSection section = testConfig.GetSection("mycustomconfigsection"); Assert.That(section != null); 

但是,看起来ConfigurationManager只会为您提供与EXE文件或计算机配置关联的配置实例。 有没有办法将任意XML加载到Configuration实例中?

实际上有一种我发现的方式….

您需要定义一个inheritance自原始配置节的新类,如下所示:

 public class MyXmlCustomConfigSection : MyCustomConfigSection { public MyXmlCustomConfigSection (string configXml) { XmlTextReader reader = new XmlTextReader(new StringReader(configXml)); DeserializeSection(reader); } } 

然后,您可以按如下方式实例化ConfigurationSection对象:

 string configXml = "..."; MyCustomConfigSection config = new MyXmlCustomConfigSection(configXml); 

希望它可以帮助某人:-)

我认为您正在寻找的是ConfigurationManager。 OpenMappedExeConfiguration

它允许您打开使用文件路径指定的配置文件(包含在ExeConfigurationFileMap中 )

如果其他海报说的是真的,并且您不希望创建一个全新的XML文件进行测试,那么我建议您将配置编辑放在Test方法本身,然后针对新更改的配置运行测试数据。

看着class上的成员,我会说答案可能不是*。 我不知道你为什么要这样做,而不是创建自己的XML配置文件。

*那不是,不包括凌乱的反思黑客