效果如下:
建議在保存時指定編碼為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;}}
}