5

I have a simple method in my class EDIDocument used to load a xml :

    /// <summary>
    /// Method used to load specific target file as template
    /// </summary>
    /// <param name="filepath">file path</param>
    /// <returns>loading status</returns>
    public bool Load(string filepath)
    {
        //file exists
        bool returnValue = File.Exists(filepath);
        //file is a xml
        returnValue &= Path.GetExtension(filepath).Equals(".xml");
        //if file is valid
        if (returnValue)
        {
            XmlReader reader = XmlReader.Create(filepath);
            //load document
            this._xmldoc = XDocument.Load(reader);
            //load complete
            returnValue &= (this._xmldoc != null);
        }
        //End of method
        return returnValue;
    }

I have a unit test for this method :

    /// <summary>
    /// Test success on load xml document
    /// </summary>
    [TestMethod]
    public void TestLoadXML_Success()
    {
        File.Create("xml.xml");
        //create document
        EDIDocument doc = new EDIDocument();
        //load something wrong
        bool result = doc.Load("xml.xml");
        //test
        Assert.IsTrue(result);
    }

I have always an exception when i start my unit test :

Test method EDIDocumentTest.TestLoadXML_Success threw exception: System.IO.IOException: The process cannot access the file 'C:......\Debug\xml.xml' because it is being used by another process.

I have googled this issue and i have tried multiple solution with XmlReader, StreamReader... by i have always the same exception...

My question is : what to do into my method Load for to fix this exception?

Thanks

Kevin ABRIOUX
  • 16,507
  • 12
  • 93
  • 99

3 Answers3

10

File.Create returns a stream to the file, so it keeps a handle open to it. You need to close the file first. This should work:

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

See this question for more details: Why is File.Create needed to be closed?

Community
  • 1
  • 1
greg84
  • 7,541
  • 3
  • 36
  • 45
2

You need to dispose of the XmlReader:

using (XmlReader reader = XmlReader.Create(filepath))
{
    //load document
    this._xmldoc = XDocument.Load(reader);
    //load complete
    returnValue &= (this._xmldoc != null);
}

You also need to change the way you create your file, like this:

File.WriteAllText("xml.xml", "");

as you never dispose of the filesystem handle used in File.Create.

It'sNotALie.
  • 22,289
  • 12
  • 68
  • 103
0

File.Create has a return value. It's a FileStream.
That FileStream holds the file.
You need to dispose of that FileStream to get access to the file:

FileStream f = File.Create("xml.xml");
f.Dispose();

or:

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

If you don't dispose of it manually, it will be disposed randomly when the GC gets to collect it... But until then it will hold the file.

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185