如何删除另一个进程使用的文件?

时间:2016-12-08 20:49:54

标签: c# visual-studio locking

在我开始之前,我应该提到这不是我想要做的事情,我只是好奇它是如何运作的。

我有一个名为AddLayer()的方法,它打开一个本地地理数据库文件并用它创建一个地图:

public async void AddLayer()
{
    try
    {
        // open a geodatabase on the local device
        gdb = await Geodatabase.OpenAsync(@"..\..\..\test.geodatabase");

        // get the first geodatabase feature table
        var gdbFeatureTable = gdb.FeatureTables.FirstOrDefault();

        //create a layer for the feature table
        lyr = new FeatureLayer
        {
            ID = gdbFeatureTable.Name,
            DisplayName = gdbFeatureTable.Name,
            FeatureTable = gdbFeatureTable
        };

        // add the graphics to the map
        MyMapView.Map.Layers.Add(lyr);
    }
    catch (Exception ex)
    {
        MessageBox.Show("Unable to create offline database: " + ex.Message);
    }

    return;
}

我还有一个名为RemoveLayer()的方法,它只是取消AddLayer()所做的所有操作,然后调用GC.Collect()

我的问题是,为什么即使不再使用文件中的资源并调用垃圾收集器,我也不能在程序运行时删除文件(地理数据库文件)? < / p>

这是Windows中所有程序的正常行为吗?是否要避免以某种方式破坏程序?

谢谢大家帮助我理解这一点。

1 个答案:

答案 0 :(得分:0)

以下代码最终为我效劳:

public void OpenGeodatabase()
{
    Geodatabase gdb = null;

    // path to .geodatabase
    var gdbPath = @"..\..\..\test.geodatabase";

    // wrap OpenAsync call in Task
    Task.Run(async () =>
    {
        // open a geodatabase on the local device
        gdb = await Geodatabase.OpenAsync(gdbPath);

    }).Wait();

    // get the first geodatabase feature table
    var gdbFeatureTable = gdb.FeatureTables.FirstOrDefault();

    // create a layer for the feature table
    var lyr = new FeatureLayer
    {
        ID = gdbFeatureTable.Name,
        DisplayName = gdbFeatureTable.Name,
        FeatureTable = gdbFeatureTable
    };

    // add the graphics to the map
    MyMapView.Map.Layers.Add(lyr);

    // remove the layer - to make it similar to case explanation
    MyMapView.Map.Layers.Remove(lyr);

    // make gdb reference null
    gdb = null;
    gdbFeatureTable = null;
    lyr = null;

    // call garbage collector
    GC.Collect();
    GC.WaitForPendingFinalizers();

    // If the works, the lock has been removed
    System.IO.File.Delete(@"..\..\..\test.geodatabase");
}

基本上我在非异步方法中做了所有事情,在一个Task中包含了对OpenAsync的调用,然后在使用后将地理数据库中的所有内容设置为null。最后,我调用了垃圾收集器并删除了文件。