IOException: file being used by another process

I know this type of questions have been asked before, and I am aware when this exception is thrown. However, I am unable to resolve it in my code.

What I have is a DataSet and I am trying to write its schema and data into a xml file.

Here is my code:

//Handler to Application.Startup Event of current Application
private void App_Startup(object sender, StartupEventArgs e)
{
    DataFile = new FileInfo("Data.xml");   //DataFile is a `System.IO.FileInfo`
    Data = new DataSet("Data");    //Data is a `System.Data.DataSet`

    if (!DataFile.Exists)
    {
        DataFile.Create();

        // Some code here that initializes `Data` (not referencing DataFile here,
        // nor doing any IO operation)

        Data.WriteXml(DataFile.FullName, XmlWriteMode.WriteSchema); //Exception is caught here
    }
}

Before I run the program, I am deleting the "Data.xml" file.

I am sure that no other process is accessing it, so there has got to be some call in my code that is not releasing the file.

What is wrong in my code?

Jon Skeet
people
quotationmark

You're calling FileInfo.Create(), which returns an open stream - but then you're not closing it, which prevents the next statement from opening the same file to read write to it.

Further, I wouldn't expect you to have to create the file first anyway - I'd expect WriteXml to do that, so you should just be able to remove the DataFile.Create(); statement entirely.

people

See more on this question at Stackoverflow