IOException:文件正在被另一个进程使用

IOException: file being used by another process

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

我有一个 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(),其中 returns 是一个打开的流 - 但是您没有关闭它,这会阻止下一条语句打开同一个文件以对其进行读写。

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