以下是我在下面粘贴的代码时遇到的错误。
无法创建ZDRCreatorTests.ZDRCreatorTests类的实例。错误:System.Configuration.ConfigurationErrorsException:无法解析属性“indexedFolder”的默认值。错误是:无法找到支持转换为/来自字符串的转换器,用于'DirectoryInfo'类型的属性'indexedFolder'。
namespace ZDRCreator
{
public class ZDRCreatorElement : ConfigurationElement
{
// Create the element.
public ZDRCreatorElement()
{ }
// Get or set the IndexedFolder
[ConfigurationProperty("indexedFolder", DefaultValue = "", IsRequired = true)]
public DirectoryInfo IndexedFolder {
get { return (DirectoryInfo)this["indexedFolder"]; }
set { this["indexedFolder"] = value; }
}
// Get or set the OutputFolder
[ConfigurationProperty("outputFolder", DefaultValue = "", IsRequired = true)]
public DirectoryInfo OutputFolder {
get { return (DirectoryInfo)this["outputFolder"]; }
set { this["outputFolder"] = value; }
}
// Get or set the ZDRFile
[ConfigurationProperty("ZDRFile", DefaultValue = "", IsRequired = true)]
public FileInfo ZDRFile {
get { return (FileInfo)this["ZDRFile"]; }
set { this["ZDRFile"] = value; }
}
// Get or set the overwriteOutput flag
[ConfigurationProperty("overwriteOutput", DefaultValue = "false", IsRequired = true)]
public bool OverwriteOutput {
get { return (bool)this["overwriteOutput"]; }
set { this["overwriteOutput"] = value; }
}
// Get or set the OutputFile
[ConfigurationProperty("outputFile", DefaultValue = "", IsRequired = true)]
public String OutputFile {
get { return (String)this["outputFile"]; }
set { this["outputFile"] = value; }
}
// Get or set the OutputFile
[ConfigurationProperty("pathMask", DefaultValue = "", IsRequired = true)]
public String PathMask {
get { return (String)this["pathMask"]; }
set { this["pathMask"] = value; }
}
}
}
我意识到错误是因为我正在尝试将一个字符串放在DirectoryInfo对象中。我的问题是:我想只存储从xml读取的字符串或原始数据类型,然后在读取xml后将它们转换为其他对象?或者,是否有一个地方可以继续将它们构建到将在内部使用的对象中。输入验证将在何处进行?
答案 0 :(得分:3)
您可以使用转换器添加TypeConventerAttribute,该转换器将从/向DirectoryInfo转换字符串(将来自配置)。转换器是从TypeConverter派生的类。
[ConfigurationProperty("ZDRFile", DefaultValue = "", IsRequired = true)]
[TypeConverter(typeof(YourCustomFileInfoTypeConverter))]
public FileInfo ZDRFile {
get { return (FileInfo)this["ZDRFile"]; }
set { this["ZDRFile"] = value; }
}
答案 1 :(得分:1)
我知道这不会直接回答您的问题,但我强烈鼓励您查看Configuration Section Designer project on CodePlex。
它将为您的应用程序中的配置部分提供设计时体验,从设计器为您生成类代码,以及将它们放入配置文件中的模板。
手动完成所有这些操作非常非常乏味,我还没有看到配置部分设计器没有处理的情况。