namespace CopyBlocks
{
using System.Collections.Generic;
using System.IO;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
public class Class1
{
[CommandMethod("CopyBlocks", CommandFlags.Session)]
public void Start()
{
var ed = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Editor;
PromptSelectionResult selection = ed.GetSelection();
if (selection.Status == PromptStatus.OK && selection.Value.Count > 0)
{
List<Entity> entities = new List<Entity>();
using (var tr = ed.Document.Database.TransactionManager.StartOpenCloseTransaction())
{
foreach (SelectedObject o in selection.Value)
{
var obj = tr.GetObject(o.ObjectId, OpenMode.ForRead) as Entity;
if(obj != null)
entities.Add(obj);
}
tr.Commit();
}
AddEntitiesToFile(entities, @"E:\Test\Test.dwg", @"E:\Test\TestNewFile.dwg");
}
}
public static void AddEntitiesToFile(
List<Entity> entities,
string templateDwgFileName,
string destDwgFileName)
{
Database db = new Database(false, true);
db.ReadDwgFile(templateDwgFileName, FileShare.Read, false, null);
db.CloseInput(true);
using (Transaction tr = db.TransactionManager.StartTransaction())
{
BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false, true);
foreach (Entity e in entities)
{
if (e is BlockReference blockReference)
{
DBObjectCollection coll = new DBObjectCollection();
blockReference.Explode(coll);
foreach (DBObject dbo in coll)
{
if (dbo is Entity entity)
{
var ent = (Entity)entity.Clone();
btr.AppendEntity(ent);
tr.AddNewlyCreatedDBObject(ent, true);
}
}
}
}
tr.Commit();
}
db.SaveAs(destDwgFileName, DwgVersion.Current);
db.Dispose();
}
}
}