[英]how can I validate dot net application config file(ex, app.exe.config) on console?
是否有任何工具来验证配置文件?
好吧,基本上你的应用程序是验证器 - 如果配置文件无效,你将在启动时遇到异常。 除此之外,我不知道对app.config文件的任何开箱即用的验证支持。
在您的目录C:\\Program Files\\Microsoft Visual Studio 9.0\\Xml\\Schemas
,您将找到一些名为DotNetConfig.xsd / DotNetConfig20.xsd
文件 - 这些是Microsoft提供的XML模式文件,您可以轻松地使用它来验证任何文件您可能拥有的其他配置文件的有效性。
以编程方式验证您的配置的基本结构将是这样的:
using(StreamReader xsdReader = new StreamReader(xsdFileName))
{
XmlSchema Schema = new XmlSchema();
Schema = XmlSchema.Read(xsdReader, new ValidationEventHandler(XSDValidationEventHandler));
XmlReaderSettings ReaderSettings = new XmlReaderSettings();
ReaderSettings.ValidationType = ValidationType.Schema;
ReaderSettings.Schemas.Add(Schema);
ReaderSettings.ValidationEventHandler += new ValidationEventHandler(XMLValidationEventHandler);
using(XmlTextReader xmlReader = new XmlTextReader(xmlFileName))
{
XmlReader objXmlReader = XmlReader.Create(xmlReader, ReaderSettings);
while (objXmlReader.Read())
{ }
}
}
Console.WriteLine("Successful validation completed!");
您现在需要做的是为那些在验证中的某些内容出错时引发的事件提供事件处理程序 - 就是这样! :-)
很老的问题,但我有同样的问题,这里是我的设置(.net框架3.5及以上):
我创建了一个名为'ConfigurationValidator'的控制台项目:
static void Main(string[] args) { try { string xsdFileName = ConfigurationManager.AppSettings["configXsdPath"]; string xmlFileName = args[0]; XmlSchemaSet schemas = new XmlSchemaSet(); schemas.Add(null, xsdFileName); XDocument doc = XDocument.Load(xmlFileName); string validationMessage = string.Empty; doc.Validate(schemas, (sender, e) => { validationMessage += e.Message + Environment.NewLine; }); if (validationMessage == string.Empty) { Console.WriteLine("CONFIG FILE IS VALID"); } else { Console.WriteLine("CONFIG FILE IS INVALID : {0}", validationMessage); } } catch(Exception ex) { Console.WriteLine("EXCEPTION VALIDATING CONFIG FILE : {0}", ex.Message); } }
和以下app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="configXsdPath" value="C:\Program Files (x86)\Microsoft Visual Studio 11.0\Xml\Schemas\DotNetConfig35.xsd"/>
</appSettings>
</configuration>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.