批量改CAD图层颜色——CAD c#二次开发

一个文件夹下大量图纸(几百甚至几千个文件)需要改图层颜色时,可采用插件实现,效果如下:

转换前:

转换后:

使用方式如下:netload加载此dll插件,输入xx运行。

附部分代码如下:

cs 复制代码
 public void ProcessDwgFile(string filePath, string savePath, string layerName, short colorIndex)
 {
     Database db = new Database(false, true); // 无文档模式

     try
     {
         // 读取DWG文件
         db.ReadDwgFile(filePath, FileOpenMode.OpenForReadAndAllShare, false, null);

         using (Transaction tr = db.TransactionManager.StartTransaction())
         {
             LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);

             // 用于存储找到的图层ID
             ObjectId layerId = ObjectId.Null;

             // 遍历所有图层名,进行不区分大小写的比较
             foreach (ObjectId id in lt)
             {
                 LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(id, OpenMode.ForRead);
                 if (ltr.Name.Equals(layerName, StringComparison.OrdinalIgnoreCase))
                 {
                     layerId = id;
                     break;
                 }
             }

             // 如果未找到图层,跳过该文件
             if (layerId.IsNull)
             {
                 tr.Commit();
                 return;
             }

             LayerTableRecord ltrToModify = (LayerTableRecord)tr.GetObject(layerId, OpenMode.ForWrite);

             // 设置图层颜色(如果选择的不是ByLayer则设置图层颜色)
             if (colorIndex != 256)
             {
                 ltrToModify.Color = Color.FromColorIndex(ColorMethod.ByAci, colorIndex);
             }

             // 修改所有图元的颜色属性
             BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
             BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);

             foreach (ObjectId entId in btr)
             {
                *****省略部分代码
             tr.Commit();
         }

         // 保存文件
         string fileName = Path.GetFileName(filePath);
         string saveFile = Path.Combine(savePath, fileName);
         db.SaveAs(saveFile, DwgVersion.Current);
     }
     catch (Exception ex)
     {
         MessageBox.Show($"处理文件 {filePath} 时出错: {ex.Message}");
     }
     finally
     {
         db.Dispose();
     }
 }

插件联系↓↓↓

相关推荐
老华带你飞33 分钟前
口腔助手|口腔挂号预约小程序|基于微信小程序的口腔门诊预约系统的设计与实现(源码+数据库+文档)
java·数据库·微信小程序·小程序·论文·毕设·口腔小程序
枫叶丹435 分钟前
【Qt开发】信号与槽(二)-> 信号和槽的使用
开发语言·qt
hqxstudying42 分钟前
J2EE模式---服务层模式
java·数据库·后端·spring·oracle·java-ee
Yu_Lijing44 分钟前
MySQL进阶学习与初阶复习第四天
数据库·学习·mysql
大熊程序猿1 小时前
net8.0一键创建支持(Orm-Sqlite-MySql-SqlServer)
数据库·mysql·sqlite
中游鱼1 小时前
如何序列化和反序列化动态 XmlElement ?
windows·microsoft·c#
Vertira1 小时前
python 阿里云 安装 dashscope的简介、安装
开发语言·python
hqxstudying3 小时前
Java异常处理
java·开发语言·安全·异常
wjs20246 小时前
状态模式(State Pattern)
开发语言
我命由我123456 小时前
Kotlin 数据容器 - List(List 概述、创建 List、List 核心特性、List 元素访问、List 遍历)
java·开发语言·jvm·windows·java-ee·kotlin·list