Question

I'm learning c# right now and I want to check if file exists. If it exists it should load and write an xml file. If it doesn't exists it should create it and after that it should load and write the xml file. But if I click my button, there comes an error:

"The process cannot access the file because it is being used by another process."

Here you can see my code:

private void btnSave_Click(object sender, EventArgs e)
{
    XElement xmlnode = new XElement("Namespace",
            new XElement("RandomText1", textBox1.Text),
            new XElement("RandomText2", textBox2.Text),
            new XElement("RandomText3", textBox3.Text)
    );

    XElement xmlFile;
    try
    {
        xmlFile = XElement.Load("testsave.xml");
        xmlFile.Add(xmlnode);
    }
    catch (XmlException)
    {
        xmlFile = new XElement("Test", xmlnode);
    }

    xmlFile.Save("testsave.xml");
    DataSet ds = new DataSet();
    ds.ReadXml("testsave.xml");
    DataTable dt = ds.Tables[0];
    dataGridView1.DataSource = dt;
}

private void Form1_Load(object sender, EventArgs e)
{
    if (!File.Exists("testsave.xml"))
    {
        File.Create("testsave.xml");
    }
}
Was it helpful?

Solution

Problem is File.Create creates a file and returns you the FileStream opened. So when you're trying to access it later you get exception. You've to close it prior to use it later.

Try this

using (File.Create("testsave.xml"))
{ }

Or

File.Create("testsave.xml").Close();

OTHER TIPS

This error happens if you open that file in another program. Close it if you have opened it in other programs and run your app again

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top