我写了一些代码,在C#窗体中,绑定到验证按钮。
代码在这里:my validation button。该代码正在使用XSD模式检查XML文件的验证。如果发生异常,则会将异常文本引发到文本框中,并且程序正在停止验证。 我想将错误/异常记录到数组中,然后将错误打印到文本框中。
如何做到这一点?如何在C#中记录异常的所有错误,然后显示?
private void validateButton_Click(object sender, System.EventArgs e)
{
resultTextBox.Text = String.Empty;
if (ValidateForm())
{
try
{
Cursor.Current = Cursors.WaitCursor;
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(String.Empty, XmlReader.Create(new StreamReader(xmlSchemaFileTextBox.Text)));
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas = schemaSet;
settings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create(new StringReader(inputXmlTextBox.Text), settings);
while (reader.Read()) { }
resultTextBox.Text = "The XML file is OK :)" +
Environment.NewLine +
DateTime.Now.ToLongDateString();
}
catch (XmlSchemaException schemaEx)
{
resultTextBox.Text = "The XML file is invalid:" +
Environment.NewLine +
schemaEx.LineNumber +
": " +
schemaEx.Message;
}
catch (Exception ex)
{
resultTextBox.Text = ex.ToString();
}
finally
{
Cursor.Current = Cursors.Default;
}
}
else
{
MessageBox.Show(null, "You have to load XML and XSD files to validate.", "There's XML file reading error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
还有没有其他办法? – sunpietro
如果要创建自己的文本,可以通过阅读Exception的Message和StackTrace属性以及可能的InnerException来创建要显示的消息文本。 –