关闭 XDOCUMENT 的实例 [英] Close instance of a XDOCUMENT

查看:20
本文介绍了关闭 XDOCUMENT 的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到此错误

进程无法访问文件C:\test\Person.xml",因为它是被另一个进程使用.IOException 未处理

在文件中保存内容后如何关闭xml文件的实例?

How do I close the instance of the xml file after saving the content in the file?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;

namespace XmlAddDelRecord
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            LoadDatagrid();
        }

        private void LoadDatagrid()
        {
            try
            {
                XmlReader xmlFile;
                xmlFile = XmlReader.Create(filePath, new XmlReaderSettings());
                DataSet ds = new DataSet();
                ds.ReadXml(xmlFile);
                dataGridView1.DataSource = ds.Tables[0];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            } 
        }

        private const string filePath = @"C:\test\Person.xml";

        private void button1_Click(object sender, EventArgs e)
        {
            var xmlDoc = new XmlDocument();

            xmlDoc.Load(filePath);

            var subRoot = xmlDoc.CreateElement("Customer");
            subRoot.SetAttribute("id", textBox6.Text.Trim());

            var firstName = xmlDoc.CreateElement("FirstName");
            var xmlTextUserName = xmlDoc.CreateTextNode(textBox1.Text.Trim());
            firstName.AppendChild(xmlTextUserName);
            subRoot.AppendChild(firstName);
            if (xmlDoc.DocumentElement != null) xmlDoc.DocumentElement.AppendChild(subRoot);

            var email = xmlDoc.CreateElement("LastName");
            var xmlTextEmail = xmlDoc.CreateTextNode(textBox2.Text.Trim());
            email.AppendChild(xmlTextEmail);
            subRoot.AppendChild(email);
            if (xmlDoc.DocumentElement != null) xmlDoc.DocumentElement.AppendChild(subRoot);

            var mobile = xmlDoc.CreateElement("Mobile");
            var xmlTextMobile = xmlDoc.CreateTextNode(textBox3.Text.Trim());

            mobile.AppendChild(xmlTextMobile);
            subRoot.AppendChild(mobile);

            if (xmlDoc.DocumentElement != null) xmlDoc.DocumentElement.AppendChild(subRoot);

            var address = xmlDoc.CreateElement("Address");
            var xmlTextAddress = xmlDoc.CreateTextNode(textBox4.Text.Trim());
            address.AppendChild(xmlTextAddress);
            subRoot.AppendChild(address);
            if (xmlDoc.DocumentElement != null) xmlDoc.DocumentElement.AppendChild(subRoot);

            var country= xmlDoc.CreateElement("Country");
            var xmlTextCountry = xmlDoc.CreateTextNode(textBox5.Text.Trim());
            country.AppendChild(xmlTextCountry);
            subRoot.AppendChild(country);

            if (xmlDoc.DocumentElement != null) xmlDoc.DocumentElement.AppendChild(subRoot);

            xmlDoc.Save(filePath);
            if (File.Exists(filePath)) return;

            var textWritter = new XmlTextWriter(filePath, null);
            textWritter.WriteStartDocument();
            textWritter.WriteStartElement("CustomerRecord");
            textWritter.WriteEndElement();

            textWritter.Close();
        }

        //Search record if not found then add a record
        private void button3_Click(object sender, EventArgs e)
        {
            XDocument doc = XDocument.Load(filePath);

            string id = textBox6.Text;
            XElement element = doc.Descendants("Customer").FirstOrDefault(p => p.Attribute("id").Value == id);

            if (element != null)
            {
                //found
                textBox6.Text = textBox6.Text;
                textBox1.Text = (string)element.Element("FirstName");
                textBox2.Text = (string)element.Element("LastName"); 
                textBox3.Text = (string)element.Element("Mobile");
                textBox4.Text = (string)element.Element("Address");
                textBox5.Text = (string)element.Element("Country");
            }
            else
            {
                //Not found
                //To add a customer
                var FirstName = textBox1.Text;
                var LastName = textBox2.Text;
                var Mobile = textBox3.Text;
                var Address = textBox4.Text;
                var Country = textBox5.Text;

                var ele = new XElement("Customer");
                ele.SetAttributeValue("id", id);
                ele.Add(new XElement("FirstName", FirstName));
                ele.Add(new XElement("LastName", LastName));
                ele.Add(new XElement("Mobile", Mobile));
                ele.Add(new XElement("Address", Address));
                ele.Add(new XElement("Country", Country));

                if (doc.Root != null) doc.Root.Add(ele);

                doc.Save(filePath, SaveOptions.None);

                dataGridView1.Refresh();
                dataGridView1.Parent.Refresh();
            }
        }

        //To Remove Record
        private void button2_Click(object sender, EventArgs e)
        {
            XDocument doc = XDocument.Load(filePath);

            var q = from node in doc.Descendants("Customer")
                    let attr = node.Attribute("id")
                    where attr != null && attr.Value == textBox6.Text 
                    select node;

            q.ToList().ForEach(x => x.Remove());
            doc.Save(filePath, SaveOptions.None);

            dataGridView1.Refresh();
            dataGridView1.Parent.Refresh();
        }
    }
}

推荐答案

XDocument.Load(string) 在加载文件后会关闭文件.如果你需要得到直接访问i/o对象,可以自己关闭:

XDocument.Load(string) does close the file after loading it. if you need to get access to the i/o object directly and can close it yourself:

XDocument document;
using (var reader = XmlReader.Create(file))
{
    document = XDocument.Load(reader);
}

似乎是其他程序正在访问此文件.

It seems be other programs accessing this file.

LoadDatagrid() 方法中更改为:

private void LoadDatagrid()
{
    try
    {
        using (XmlReader xmlFile = XmlReader.Create(filePath, 
                                                    new XmlReaderSettings()))
        {
            DataSet ds = new DataSet();
            ds.ReadXml(xmlFile);
            dataGridView1.DataSource = ds.Tables[0];
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

你必须Close/Dispose你的XmlReader

这篇关于关闭 XDOCUMENT 的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆