Purge Unreferenced Named Objects (.NET)

Unreferenced named objects can be purged from a database at any time. You cannot purge named objects that are referenced by other objects. For example, a font file might be referenced by a text style or a layer might be referenced by the objects on that layer. Purging reduces the size of a drawing file when saved to disk.

Unreferenced objects are purged from a drawing database with the Purge method. The Purge method requires a list of objects you want to purge in the form of an ObjectIdCollection or ObjectIdGraph objects. The ObjectIdCollection or ObjectIdGraph objects passed into the Purge method are updated with the objects in which can be erased from the database. After the call to Purge, you must erase each individual object returned.

Purge all unreferenced layers

The following example demonstrates how to purge all unreferenced layers from a database.

C# Example

using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
 
[CommandMethod("PurgeUnreferencedLayers")]
public static void PurgeUnreferencedLayers()
{
    // Get the current document and database
    Document acDoc = Application.DocumentManager.MdiActiveDocument;
    Database acCurDb = acDoc.Database;

    // Start a transaction
    using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
    {
        // Open the Layer table for read
        LayerTable acLyrTbl;
        acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
                                     OpenMode.ForRead) as LayerTable;

        // Create an ObjectIdCollection to hold the object ids for each table record
        ObjectIdCollection acObjIdColl = new ObjectIdCollection();

        // Step through each layer and add iterator to the ObjectIdCollection
        foreach (ObjectId acObjId in acLyrTbl)
        {
            acObjIdColl.Add(acObjId);
        }

        // Remove the layers that are in use and return the ones that can be erased
        acCurDb.Purge(acObjIdColl);

        // Step through the returned ObjectIdCollection
        // and erase each unreferenced layer
        foreach (ObjectId acObjId in acObjIdColl)
        {
            SymbolTableRecord acSymTblRec;
            acSymTblRec = acTrans.GetObject(acObjId,
                                            OpenMode.ForWrite) as SymbolTableRecord;

            try
            {
                // Erase the unreferenced layer
                acSymTblRec.Erase(true);
            }
            catch (Autodesk.AutoCAD.Runtime.Exception Ex)
            {
                // Layer could not be deleted
                Application.ShowAlertDialog("Error:\n" + Ex.Message);
            }
        }

        // Commit the changes and dispose of the transaction
        acTrans.Commit();
    }
}