【问题标题】:IOException: file being used by another processIOException: 文件正被另一个进程使用
【发布时间】:2016-12-24 23:02:59
【问题描述】:

我知道以前有人问过此类问题,并且我知道何时抛出此异常。但是,我无法在我的代码中解决它。

我拥有的是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”文件。

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

我的代码有什么问题?

【问题讨论】:

  • 你希望你的代码做什么?你的文字说你想写,你的方法叫做读,你的文件是空的。
  • @nvoigt 对不起,我的错。问问题时犯了错误。 PL。检查编辑。

标签: c# xml wpf dataset


【解决方案1】:

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

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

【讨论】:

  • 对不起,我的错。问问题时犯了错误。 PL。检查编辑。
  • @VijayChavda:好的,我已经删除了中间那段 - 答案的其余部分仍然有效。
猜你喜欢
  • 2011-09-04
  • 1970-01-01
  • 2021-02-27
  • 1970-01-01
  • 2018-09-20
  • 2020-03-11
  • 1970-01-01
  • 2011-04-13
相关资源
最近更新 更多