Code:
public static ObjectId InsertBlock ( Database db, string loName, string blkName, Point3d insPt ) {
ObjectId RtnObjId = ObjectId.Null;
using ( Transaction Trans = db.TransactionManager.StartTransaction( ) ) {
DBDictionary LoDict = Trans.GetObject( db.LayoutDictionaryId, OpenMode.ForRead ) as DBDictionary;
foreach ( DictionaryEntry de in LoDict ) {
if ( string.Compare( ( string )de.Key, loName, true ).Equals( 0 ) ) {
Layout Lo = Trans.GetObject( ( ObjectId )de.Value, OpenMode.ForWrite ) as Layout;
BlockTable BlkTbl = Trans.GetObject( db.BlockTableId, OpenMode.ForRead ) as BlockTable;
BlockTableRecord LoRec = Trans.GetObject( Lo.BlockTableRecordId, OpenMode.ForRead ) as BlockTableRecord;
ObjectId BlkTblRecId = GetNonErasedTableRecordId( BlkTbl.Id, blkName );
if ( BlkTblRecId.IsNull ) {
string BlkPath = HostApplicationServices.Current.FindFile( blkName + ".dwg", db, FindFileHint.Default );
if ( string.IsNullOrEmpty( BlkPath ) )
return RtnObjId;
BlkTbl.UpgradeOpen( );
using ( Database tempDb = new Database( false, true ) ) {
tempDb.ReadDwgFile( BlkPath, FileShare.Read, true, null );
db.Insert( blkName, tempDb, false );
}
BlkTblRecId = GetNonErasedTableRecordId( BlkTbl.Id, blkName );
}
LoRec.UpgradeOpen( );
BlockReference BlkRef = new BlockReference( insPt, BlkTblRecId );
LoRec.AppendEntity( BlkRef );
Trans.AddNewlyCreatedDBObject( BlkRef, true );
BlockTableRecord BlkTblRec = Trans.GetObject( BlkTblRecId, OpenMode.ForRead ) as BlockTableRecord;
if ( BlkTblRec.HasAttributeDefinitions ) {
foreach ( ObjectId objId in BlkTblRec ) {
AttributeDefinition AttDef = Trans.GetObject( objId, OpenMode.ForRead ) as AttributeDefinition;
if ( AttDef != null ) {
AttributeReference AttRef = new AttributeReference( );
AttRef.SetAttributeFromBlock( AttDef, BlkRef.BlockTransform );
BlkRef.AttributeCollection.AppendAttribute( AttRef );
Trans.AddNewlyCreatedDBObject( AttRef, true );
}
}
}
Trans.Commit( );
}
}
}
return RtnObjId;
}
This is my sub...... ' GetNonErasedTableRecordId ' is Tony T.'s code, so you might have to search for it, but it does just what the title says.