我想创建一个“另存为”按钮,它将使用.xsd XML模式验证dataGridView中的数据,然后再将其保存为XML文件。我们的想法是将填充了DGV数据的DataTable保存为XML,使用.xsd进行验证并在文件有效时将其删除,但只要文件正在使用就不可能。请帮忙。
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog win = new SaveFileDialog();
win.InitialDirectory = "e:\\";
win.Filter = "XML document (xml)|*.xml";
if (win.ShowDialog() == DialogResult.OK)
{
string file_name = win.FileName;
DataTable table = new DataTable();
table = (DataTable) dataGridView1.DataSource;
table.WriteXml(file_name);
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(null, "e:/katalog.xsd");
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
XmlReader read = XmlReader.Create(file_name, settings);
do
{
read.Read();
}
while (!f);
if (!f)
{
File.Delete(file_name);
}
f = true;
}
}
static bool f = true;
static void ValidationEventHandler(object sender, ValidationEventArgs e)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
Console.WriteLine("Error: {0}", e.Message);
f = false;
break;
case XmlSeverityType.Warning:
Console.WriteLine("Warning {0}", e.Message);
f = false;
break;
}
}
答案 0 :(得分:2)
If the question is why can't the file be deleted, it is because the XmlReader has the file open - call read.Close() before trying to delete the file.