当前位置: 首页 > news >正文

导出cad实体所有信息到txt并打开(生成唯一文件名) ——c#cad二次开发

效果如下:

建议在保存时指定编码为UTF-8:

using (StreamWriter sw = new StreamWriter(filePath, false, Encoding.UTF8))

     {

         // 写入内容

     }

最终

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text;
using Path = System.IO.Path;
namespace EnhancedEntityPropertyExporter
{
    public class ExportCommands
    {
        [CommandMethod("xx")]
        public void 属性查询()
        {
            List<Entity> ents = SelectEntities<Entity>();
            if (ents is null || ents.Count == 0)
            {
                Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("未选择!\n");
                return;
            }

            try
            {
                // 获取桌面路径
                string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

                // 生成基础文件名(格式:图元属性20231010)
                string baseFileName = $"图元属性{DateTime.Now:yyyyMMddhhmmss}";
                string fullPath = "";
                int copyNumber = 0;

                // 生成唯一文件名
                do
                {
                    string suffix = copyNumber > 0 ? $"复件{copyNumber}" : "";
                    string fileName = $"{baseFileName}{suffix}.txt";
                    fullPath = Path.Combine(desktopPath, fileName);
                    copyNumber++;
                } while (File.Exists(fullPath)); // 循环直到找到不存在的文件名

                // 构建属性字符串
                using (StreamWriter sw = new StreamWriter(fullPath, false, System.Text.Encoding.UTF8))
                {

                   

                    foreach (var obj in ents)
                    {

                        sw.WriteLine($"AutoCAD 实体属性导出 - {DateTime.Now}");

                        sw.WriteLine("====================================");

                        sw.WriteLine($"实体类型: {obj.GetType().Name}");

                        sw.WriteLine($"句柄(Handle): {obj.Handle}");

                        sw.WriteLine($"图层(Layer): {obj.Layer}");

                        sw.WriteLine("====================================");

                        sw.WriteLine();

                        string str = "";
                        str += "对象全部属性:  >\n";
                        str += $"类型:    {obj.GetType()}\n";

                        PropertyInfo[] pis = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
                        foreach (var pi in pis)
                        {
                            try
                            {
                                var value = pi.GetValue(obj, null);
                                str += $"{pi.Name} :    {(value != null ? value.ToString() : "Null")}\n";
                            }
                            catch
                            {
                                str += $"{pi.Name} :    获取失败\n";
                            }
                        }
                        str += "\n";
                        sw.Write(str); // 写入文件
                    }
                }

                // 用记事本打开文件
                Process.Start("notepad.exe", fullPath);

            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出失败:{ex.Message}");
            }
        }

        public List<T> SelectEntities<T>() where T : Entity
        {
            List<T> result = new List<T>();
            Editor editor = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            var pso = new PromptSelectionOptions();
            pso.MessageForAdding = "\n请选择:";
            PromptSelectionResult psr = editor.GetSelection(pso);
            if (psr.Status == PromptStatus.OK)
            {
                ObjectId[] objectids = psr.Value.GetObjectIds();
                Database database = HostApplicationServices.WorkingDatabase;
                using (Transaction tran = database.TransactionManager.StartTransaction())
                {
                    foreach (var item in objectids)
                    {
                        Entity entity = item.GetObject(OpenMode.ForRead) as Entity;
                        if (entity is T)
                        {
                            result.Add(entity as T);
                        }

                    }
                }
            }
            return result;
        }
    }
}

相关文章:

  • 大数据技术之Scala
  • 5、无线通信基站的FPGA实现架构
  • 大厂算法面试 7 天冲刺:第2天-链表算法深度解析 - 高频面试题与Java实战
  • OpenCv(五)——边缘检测
  • 基础算法篇(3)(蓝桥杯常考点)—图论
  • 【Java】Hibernate的一级缓存
  • 多模态大语言模型arxiv论文略读(一)
  • Mac下小智AI本地环境部署
  • MetaPerceptron:基于200+种优化算法的多层感知器MLP参数优化-附Python免费代码
  • 将pandas.DataFrame转换为以数据为键的字典
  • 【FPGA开发】用 Verilog编程实现一个分秒计数器(实现按键暂停、消抖功能)
  • 关于UDP端口扫描概述
  • Vue表单数据回显失败技术解析与修复指南!!!
  • RapidJSON 处理 JSON(高性能 C++ 库)(四)
  • 检查是否存在占用内存过大的SQL
  • 服务器入门操作1(深度学习)
  • 【Deepseek、ChatGPT】智能气候前沿:AI Agent结合机器学习与深度学习在全球气候变化驱动因素预测中的应用
  • 高通Android10 铃声通话音频80%音量修改
  • 【Easylive】transferVideoFile 方法详细解析
  • 边缘计算的崛起:当计算从“云端漫步“变成“街头快闪“
  • 永辉超市回应顾客结算时被“反向抹零”:整改并补偿
  • “女乘客遭顺风车深夜丢高速服务区”续:滴滴永久封禁两名涉事司机账号
  • 上海“模速空间”:将形成人工智能“北斗七星”和群星态势
  • 民生银行一季度净利127.42亿降逾5%,营收增7.41%
  • 国务院安委会对辽宁辽阳一饭店重大火灾事故查处挂牌督办
  • 被算法重塑的世界,人与技术如何和谐共处