Find the below code, Alter as per your needs.
Find the code below, Alter as per your needs...
public void AddBlocktoDataBase()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
using (Database OpenDb = new Database(false, true))
{
PromptStringOptions pStrOpts = new PromptStringOptions("Ask for the template like 1,2,3,4,etc");
pStrOpts.AllowSpaces = false;
PromptResult pStrRes = doc.Editor.GetString(pStrOpts);
if (pStrRes.Status != PromptStatus.OK)
return;
if (pStrRes.StringResult.Equals("1"))
{
OpenDb.ReadDwgFile("Template path here", System.IO.FileShare.ReadWrite, true, "");
blkname = "TPS-A1-Manufacturing-India";
}
ObjectIdCollection ids = new ObjectIdCollection();
using (Transaction tr = OpenDb.TransactionManager.StartTransaction())
{
//For example, Get the block by name "BlkName"
BlockTable bt;
bt = (BlockTable)tr.GetObject(OpenDb.BlockTableId, OpenMode.ForRead);
if (bt.Has(blockkname))
{
ids.Add(bt[blockname]);
}
tr.Commit();
}
//if found, add the block
if (ids.Count != 0)
{
//get the current drawing database
Database destdb = doc.Database;
IdMapping iMap = new IdMapping();
destdb.WblockCloneObjects(ids, destdb.BlockTableId, iMap, DuplicateRecordCloning.Ignore, false);
}
}
}
public void AddBlocktoModelSpace()
{
Database db = Application.DocumentManager.MdiActiveDocument.Database;
using (Transaction myT = db.TransactionManager.StartTransaction())
{
//Get the block definition "Check".
BlockTable bt = db.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable;
BlockTableRecord blockDef = bt[blockname].GetObject(OpenMode.ForRead) as BlockTableRecord;
//Also open modelspace - we'll be adding our BlockReference to it
BlockTableRecord ms = bt[BlockTableRecord.ModelSpace].GetObject(OpenMode.ForWrite) as BlockTableRecord;
//Create new BlockReference, and link it to our block definition
using (BlockReference blockRef = new BlockReference(insertionpoint, blockDef.ObjectId))
{
//Add the block reference to modelspace
ms.AppendEntity(blockRef);
myT.AddNewlyCreatedDBObject(blockRef, true);
//Iterate block definition to find all non-constant
// AttributeDefinitions
foreach (ObjectId id in blockDef)
{
DBObject obj = id.GetObject(OpenMode.ForRead);
AttributeDefinition attDef = obj as AttributeDefinition;
if ((attDef != null) && (!attDef.Constant))
{
//This is a non-constant AttributeDefinition
//Create a new AttributeReference
using (AttributeReference attRef = new AttributeReference())
{
attRef.SetAttributeFromBlock(attDef, blockRef.BlockTransform);
//attRef.TextString = "Santosh";
//Add the AttributeReference to the BlockReference
blockRef.AttributeCollection.AppendAttribute(attRef);
myT.AddNewlyCreatedDBObject(attRef, true);
}
}
}
}
//Our work here is done
myT.Commit();
}
}