Purging anonymous blocks

By Daniel Du

Issue

How do I purge all unnamed (and unreferenced) blocks from a drawing programmatically?

Solution

To purge all unreferenced objects from a drawing, you can use the PurgeAll command.

VBA Code

Sub del_all()
    ThisDrawing.Application.ActiveDocument.PurgeAll()
End Sub

.NET (C#) Code

This sample deletes all unreferenced blocks by iterating through the Block Table:

[CommandMethod("ClearUnrefedBlocks")]
public void ClearUnrefedBlocks()
{
    Document doc = Application.DocumentManager.MdiActiveDocument;
    Editor ed = doc.Editor;
    Database db = doc.Database;

    using (Transaction trans = db.TransactionManager.StartTransaction())
    {
        BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;

        foreach (ObjectId oid in bt)
        {
            BlockTableRecord btr = trans.GetObject(oid, OpenMode.ForWrite) as BlockTableRecord;

            if (btr.GetBlockReferenceIds(false, false).Count == 0 && !btr.IsLayout)
            {
                btr.Erase();
            }
        }
        trans.Commit();
    }
}

Alternative Option: Wblock

Another option is to use Wblock. Any unreferenced symbols in the input database are omitted in the new database, which makes the new database potentially cleaner and smaller than the original.

[CommandMethod("ClrDb")]
public void ClearDatabase()
{
    Document doc = Application.DocumentManager.MdiActiveDocument;
    Editor ed = doc.Editor;
    Database db = doc.Database;

    Database newDb = db.Wblock();
    newDb.SaveAs(@"C:\temp\clrdb.dwg", DwgVersion.Current);
}

Comments

3 responses to “Purging anonymous blocks”

  1. Norman Yuan Avatar
    Norman Yuan

    This is VBA code and it has access to AcadApplication object directly. Why use version specific GetObject(,”AutoCAD.Application.19″)? It is completely not necessary to possibly mislead newbies. Code like this from Autodesk dev team is a bit disappointing.

  2. Thanks Norman for the comment, The code was in VB. To be clear, I changed it to VBA code and appended some C# code snippet for reference.

  3. How about an example launching AcCoreConsole programatically?

Leave a Reply

Discover more from Autodesk Developer Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading