[英]Writing an XmlSchema to a MemoryStream fails with an exception while running from Nunit
I'm trying to convert an XmlSchema object to string. 我正在尝试将XmlSchema对象转换为字符串。
I'm building a simple XmlSchema, compiling it, and then converting it as follows: 我正在构建一个简单的XmlSchema,对其进行编译,然后按如下所示进行转换:
public string ConvertXmlSchemaToString(XmlSchema xmlSchema)
{
String schemaAsString = String.Empty;
// compile the schema
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(xmlSchema);
schemaSet.ValidationEventHandler += new ValidationEventHandler(schemaSet_ValidationEventHandler);
schemaSet.Compile();
// allocate memory for string output
MemoryStream memStream = new MemoryStream(1024);
xmlSchema.Write(memStream);
memStream.Seek(0, SeekOrigin.Begin);
StreamReader reader = new StreamReader(memStream);
schemaAsString = reader.ReadToEnd();
return schemaAsString;
}
While running as a console app, everything works fine, but when running from Nunit I get an exception in the "xmlSchema.Write(memStream);" 作为控制台应用程序运行时,一切正常,但是从Nunit运行时,我在“ xmlSchema.Write(memStream);”中遇到异常。 line. 线。
exception is : There was an error generating the XML document. 例外是:生成XML文档时出错。
inner exception is : Common Language Runtime detected an invalid program. 内部异常是:公共语言运行库检测到无效程序。
Probably won't fix your problem, but you might want to wrap usings around your streams like so. 可能无法解决您的问题,但是您可能希望像这样在流周围包装用法。
// allocate memory for string output
using (MemoryStream MemStream = new MemoryStream(1024))
{
xmlSchema.Write(MemStream);
MemStream.Seek(0, SeekOrigin.Begin);
using (StreamReader reader = new StreamReader(MemStream))
{
SchemaAsString = reader.ReadToEnd();
}
}
return SchemaAsString;
That way the streams are disposed of properly. 这样就可以正确处理流。 That might be what NUnit is complaining about. 这可能是NUnit抱怨的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.