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);
}

Leave a Reply