gpt4 book ai didi

c# - 无法访问简单文件 "because it is being used by another process"

转载 作者:太空狗 更新时间:2023-10-30 00:15:01 24 4
gpt4 key购买 nike

我的类 EDIDocument 中有一个简单的方法用于加载 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;
}

我有这个方法的单元测试:

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

当我开始我的单元测试时总是出现异常:

测试方法 EDIDocumentTest.TestLoadXML_Success 抛出异常:System.IO.IOException: 进程无法访问文件 'C:......\Debug\xml.xml' 因为它正被另一个进程使用

我用谷歌搜索了这个问题,我尝试了 XmlReader、StreamReader 的多种解决方案......我总是有相同的异常......

我的问题是:如何对我的 Load 方法做些什么来修复这个异常?

谢谢

最佳答案

File.Create 向文件返回一个流,因此它保持一个句柄打开。您需要先关闭文件。这应该有效:

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

有关详细信息,请参阅此问题:Why is File.Create needed to be closed?

关于c# - 无法访问简单文件 "because it is being used by another process",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17860746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com