- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report
I get following exception when I debug the code below, can anyone help what is the reason? I am not able to find solution in the forum.
I have following dependencies:
code:
using System;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Point3d point1 = new Point3d(0, 0, 0);
string blkN = "C:/E_Cable.dwg";
InsertBlock(point1, blkN);
}
public static void InsertBlock(Point3d insPt, string blockName)
{
var doc = Application.DocumentManager.MdiActiveDocument;
var db = doc.Database;
var ed = doc.Editor;
using (var tr = db.TransactionManager.StartTransaction())
{
// check if the block table already has the 'blockName'" block
var bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
if (!bt.Has(blockName))
{
try
{
// search for a dwg file named 'blockName' in AutoCAD search paths
var filename = HostApplicationServices.Current.FindFile(blockName + ".dwg", db, FindFileHint.Default);
// add the dwg model space as 'blockName' block definition in the current database block table
using (var sourceDb = new Database(false, true))
{
sourceDb.ReadDwgFile(filename, FileOpenMode.OpenForReadAndAllShare, true, "");
db.Insert(blockName, sourceDb, true);
}
}
catch
{
ed.WriteMessage($"\nBlock '{blockName}' not found.");
return;
}
}
// create a new block reference
using (var br = new BlockReference(insPt, bt[blockName]))
{
var space = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
space.AppendEntity(br);
tr.AddNewlyCreatedDBObject(br, true);
}
tr.Commit();
}
}
}
}
Solved! Go to Solution.