输出块定义中所有实体信息
如图,通过选择块参照找到对应的块定义,输出块定义所有图元所有属性信息到桌面txt文档。
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using System;
using System.IO;
using Path = System.IO.Path;
namespace CadBlockExport命名空间可以修改吗
{
public class Commands
{
[CommandMethod("xx")]
public static void 块demo()
{
// 获取当前文档和数据库
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
// 提示用户选择块参照
PromptEntityOptions peo = new PromptEntityOptions("\n选择一个块参照: ");
peo.SetRejectMessage("\n选择的对象不是块参照,请重新选择。");
peo.AddAllowedClass(typeof(BlockReference), true);
PromptEntityResult per = ed.GetEntity(peo);
if (per.Status != PromptStatus.OK) return;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
// 打开所选的块参照
BlockReference blockRef = tr.GetObject(per.ObjectId, OpenMode.ForRead) as BlockReference;
if (blockRef == null)
{
ed.WriteMessage("\n所选对象不是有效的块参照。");
tr.Commit();
return;
}
// 获取块定义
BlockTableRecord blockDef = tr.GetObject(blockRef.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
if (blockDef == null)
{
ed.WriteMessage("\n无法获取块定义。");
tr.Commit();
return;
}
// 获取桌面路径
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string baseFileName = "BlockInfo.txt";
string filePath = Path.Combine(desktopPath, baseFileName);
int copyCount = 1;
// 检查文件是否存在,如果存在则添加 "副本" 字样
while (File.Exists(filePath))
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(baseFileName);
string extension = Path.GetExtension(baseFileName);
filePath = Path.Combine(desktopPath, $"{fileNameWithoutExtension} 副本{copyCount}{extension}");
copyCount++;
}
try
{
// 打开文件进行写入
using (StreamWriter sw = new StreamWriter(filePath))
{
// 写入块参照的位置
sw.WriteLine($"块参照位置: {blockRef.Position}");