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
Applies to: Press Ctrl + Alt + Delete, then click Task Manager. Ensure you're on the Processes tab. Locate and right-click SidekickTrayWPF, then select End Process. If a warning window opens to ask if you want to end the process, click End Process again to confirm.
This error usually means that either the user or someone else still has that file open. This can happen if the file referenced is open in another program or if a crash occurs while uploading.
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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With