I realize that this posting is 10 years old, so I might not get a response. However, I am having difficulty figuring out how to remove .sr lock files from shapefiles using ArcObjects and C# after removing the associated layer from the map. I notice that using the straight UI in ArcMap that removing a layer will remove the lock file, but I cannot get this to happen programmatically. I have tried everything that I can think of, including calling Marshal.FinalReleaseComObject on all variables.
The IMxDocument.OperationStack might still have a reference to the layer.
Maybe try IOperationStack.Reset() to see if that clears the lock. You won't be able to Edit>Undo (ctrl-Z) to the layer removal after doing so.
Kirk, thank you for the response. I tried your suggestion and unfortunately it did not make a difference. The only thing that seems to kill the .sr.lock files is manually shutting down the ArcMap application, which gets rid of all of the COM references. However, this is not a solution, since I have so many directories worth of shapefiles to run through. The following is a little snippet from my code to show the issue.
pGxObjects.Reset();
while ((pGxDataset = (IGxDataset)pGxObjects.Next()) != null)
{
IFeatureLayer pFeatLayer = new FeatureLayer();
pFeatLayer.FeatureClass = (IFeatureClass)pGxDataset.Dataset;
pFeatLayer.Name = pFeatLayer.FeatureClass.AliasName;
pMxDoc.FocusMap.AddLayer(pFeatLayer);
// Do something with the layer
pMxDoc.FocusMap.DeleteLayer(pFeatLayer);
Marshal.FinalReleaseComObject(pFeatLayer);
Marshal.FinalReleaseComObject(pGxDataset);
}
Marshal.FinalReleaseComObject(pGxObjects);
GC.Collect();
GC.WaitForPendingFinalizers();
Maybe before deleting the layer, try IDataLayer2.Disconnect() on it.
That was a great suggestion. I had forgotten about IDataLayer2. However, it did not work. The lock file is still there. I have noticed that the lock file isn't actually created when the layer is added to the map, but two lines earlier when the feature class is defined on the feature layer from pGxDataset.Dataset (for whatever help that is).
In general, I find it good practice to work with IName objects.
Maybe try replacing this:
pFeatLayer.FeatureClass = (IFeatureClass)pGxDataset.Dataset;
with this:
pFeatLayer.FeatureClass = ((IName)pGxDataset.DatasetName).Open() as IFeatureClass;
That was another good suggestion, but unfortunately I have the same result. The .sr.lock file is created and I can't remove it.