Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8366013
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T12:48:11+00:00 2026-06-09T12:48:11+00:00

I’m getting this error The process cannot access the file ‘C:\test\Person.xml’ because it is

  • 0

I’m getting this error

The process cannot access the file ‘C:\test\Person.xml’ because it is
being used by another process. IOException was UnHandled

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();
        }
    }
}

enter image description here

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T12:48:12+00:00Added an answer on June 9, 2026 at 12:48 pm

    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.


    in the LoadDatagrid() method change to this:

    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());
        }
    }
    

    You have to Close/Dispose your XmlReader

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
In my XML file chapters tag has more chapter tag.i need to display chapters
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I'm parsing an XML file, the creators of it stuck in a bunch social
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I used javascript for loading a picture on my website depending on which small

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.