封装写块 blocktool _c#

    public static class blocktool
    {
         public static ObjectId addCurvesToBlock(this List curves, string blockName, Point3d basePoint)
         {
            // 获取当前文档和数据库
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor editor = doc.Editor;

            // 启动事务处理
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    // 打开块表以进行读操作
                    BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);

                    // 检查块表记录是否已经存在
                    if (bt.Has(blockName))
                    {
                        editor.WriteMessage("\n块表记录 {0} 已经存在。", blockName);
                        return ObjectId.Null;
                    }

                    // 打开块表以进行写操作
                    bt.UpgradeOpen();

                    // 创建一个新的块表记录
                    BlockTableRecord btr = new BlockTableRecord();
                    btr.Name = blockName;

                    // 将新的块表记录添加到块表中
                    ObjectId btrId = bt.Add(btr);
                    tr.AddNewlyCreatedDBObject(btr, true);

                    // 遍历传入的 Curve 列表
                    foreach (Curve curve in curves)
                    {
                        // 克隆曲线对象
                        Curve clonedCurve = (Curve)curve.Clone();

                        // 将克隆的曲线添加到块表记录中
                        btr.AppendEntity(clonedCurve);
                        btr.Origin = basePoint;
                        tr.AddNewlyCreatedDBObject(clonedCurve, true);
                    }

                    // 提交事务
                    tr.Commit();
                    editor.WriteMessage($"\n成功将曲线写入块表记录 {blockName}。");
                    return btrId;
                   
                }
                catch (System.Exception ex)
                {
                    // 处理异常并输出错误信息
                    editor.WriteMessage("\n操作出错: {0}", ex.Message);
                    return ObjectId.Null;
                }
            }
         }
    }

你可能感兴趣的:(CAD,C#二次开发,数据库)