Explode CAD Blocks using .Net

I’ve been playing a lot with AutoCAD API in the past days. This a function that will help you exploding block references if you provide the Block’s Name.

Feel free to use, improve and share.

	public bool ExplodeBlockByNameCommand(string blockToExplode)
	{
    	bool explodeResult = true;
        Document bDwg = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
        Editor ed = bDwg.Editor;
        Database db = bDwg.Database;
        Autodesk.AutoCAD.DatabaseServices.TransactionManager bTransMan = bDwg.TransactionManager;
        using (Transaction bTrans = bTransMan.StartTransaction())
        {
	        try {
    	         BlockTable bt = (BlockTable)bTrans.GetObject(db.BlockTableId, OpenMode.ForRead);

				ed.WriteMessage("nProcessing {0}", blockToExplode);

                if (bt.Has(blockToExplode))
                {
                	ObjectId blkId = bt[blockToExplode];
                    BlockTableRecord btr = (BlockTableRecord)bTrans.GetObject(blkId, OpenMode.ForRead);
                    ObjectIdCollection blkRefs = btr.GetBlockReferenceIds(true, true);

                    foreach (ObjectId blkXId in blkRefs)
                    {
				    	//create collection for exploded objects
                        DBObjectCollection objs = new DBObjectCollection();

                        //handle as entity and explode
                        Entity ent = (Entity)bTrans.GetObject(blkXId, OpenMode.ForRead);
                        ent.Explode(objs);
                        ed.WriteMessage("nExploded an Instance of {0}", blockToExplode);

                        //erase Block
                        ent.UpgradeOpen();
                        ent.Erase();

                        BlockTableRecord btrCs = (BlockTableRecord)bTrans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);

						foreach (DBObject obj in objs)
                        {
                        	Entity ent2 = (Entity)obj;
                            btrCs.AppendEntity(ent2);
                            bTrans.AddNewlyCreatedDBObject(ent2, true);
                        }

               		}
               	}

                bTrans.Commit();
			} catch {
            	ed.WriteMessage("nSomething went wrong");
                explodeResult = false;
            } finally {
        	}
    	    ed.WriteMessage("n");
	        bTrans.Dispose();
        	bTransMan.Dispose();
    	}

    	return explodeResult; //return wheter the method was succesful or not

	}