gpt4 book ai didi

c# - IO异常 : file being used by another process

转载 作者:太空宇宙 更新时间:2023-11-03 18:04:18 25 4
gpt4 key购买 nike

我知道以前有人问过这种类型的问题,我知道什么时候抛出这个异常。但是,我无法在我的代码中解决它。

我有一个 DataSet,我正在尝试将其架构和数据写入 xml 文件。

这是我的代码:

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

在运行程序之前,我要删除“Data.xml”文件。

我确信没有其他进程正在访问它,所以我的代码中肯定有一些调用没有释放文件。

我的代码有什么问题?

最佳答案

您正在调用 FileInfo.Create() ,它返回一个打开的流 - 但随后您没有关闭它,这会阻止下一条语句打开同一文件以对其进行读写。

此外,我不希望您必须先创建文件 - 我希望 WriteXml 可以这样做,因此您应该能够删除 DataFile。 Create(); 完全声明。

关于c# - IO异常 : file being used by another process,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39011014/

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