C# 如何模拟.config文件的file属性';应用程序设置部分
Microsoft允许将C# 如何模拟.config文件的file属性';应用程序设置部分,c#,app-config,C#,App Config,Microsoft允许将.config文件的appSettings部分引用另一个文件:例如: <appSettings file="c:\commonSettings.config"> <add key="myAppSpecificSetting" value="Setting1" /> </appSettings> 并不是一般的.config文件功能 现在,我已经实现了自己的ConfigurationSection,并且希望能够像使用appSett
.config
文件的appSettings
部分引用另一个文件:例如:
<appSettings file="c:\commonSettings.config">
<add key="myAppSpecificSetting" value="Setting1" />
</appSettings>
并不是一般的.config
文件功能
现在,我已经实现了自己的ConfigurationSection
,并且希望能够像使用appSettings
一样指定file=
。除了简单地创建属性以匹配属性并检索文件名之外,我还可以如何在自定义的configSection
?中实际重新创建/模拟此功能。看起来它只是通过appsetings部分
读取文件系统来实现的,没有什么特别的东西可以在您自己的配置部分重用
protected internal override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
{
string ElementName = reader.Name;
base.DeserializeElement(reader, serializeCollectionKey);
if ((File != null) && (File.Length > 0)) {
string sourceFileFullPath;
string configFileDirectory;
string configFile;
// Determine file location
configFile = ElementInformation.Source;
if (String.IsNullOrEmpty(configFile)) {
sourceFileFullPath = File;
}
else {
configFileDirectory = System.IO.Path.GetDirectoryName(configFile);
sourceFileFullPath = System.IO.Path.Combine(configFileDirectory, File);
}
if (System.IO.File.Exists(sourceFileFullPath)) {
int lineOffset = 0;
string rawXml = null;
using (Stream sourceFileStream = new FileStream(sourceFileFullPath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
using (XmlUtil xmlUtil = new XmlUtil(sourceFileStream, sourceFileFullPath, true)) {
if (xmlUtil.Reader.Name != ElementName) {
throw new ConfigurationErrorsException(
SR.GetString(SR.Config_name_value_file_section_file_invalid_root, ElementName),
xmlUtil);
}
lineOffset = xmlUtil.Reader.LineNumber;
rawXml = xmlUtil.CopySection();
// Detect if there is any XML left over after the section
while (!xmlUtil.Reader.EOF) {
XmlNodeType t = xmlUtil.Reader.NodeType;
if (t != XmlNodeType.Comment) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_source_file_format), xmlUtil);
}
xmlUtil.Reader.Read();
}
}
}
ConfigXmlReader internalReader = new ConfigXmlReader(rawXml, sourceFileFullPath, lineOffset);
internalReader.Read();
if (internalReader.MoveToNextAttribute()) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_base_unrecognized_attribute, internalReader.Name), (XmlReader)internalReader);
}
internalReader.MoveToElement();
base.DeserializeElement(internalReader, serializeCollectionKey);
}
}
}
我看到了这个方法(请参阅我问题中的源代码链接),但不知道它涉及到了什么(不过我现在看到了文件属性引用)。DeserializeElement什么时候会被调用?我不太清楚,但我假设它在ConfigurationManager内部的某个地方。self注意:在您试图理解的类中,请始终查看override
方法,因为它们可以将自定义功能连接到基类功能……不幸的是,这并没有真正的帮助。我无法复制该功能,因为我无法在自己的类中重写反序列化元素
方法。。。回到绘图板上。