天天看点

C# AutoCAD 通过C#代码生成DWG文件

引用都是一些基本的引用. 其实挺简单的, 只是刚开始不清楚方法会比较痛苦, 因为没有头绪. 后来找到了Document有一个CloseAndSave()方法便试着用了一下. 效果比较简陋但能用了.

/// <summary>
/// 这个方法将创建DWG文件
/// </summary>
/// <param name="solid3d">实体对象</param>
/// <param name="strCableName">文件名</param>
/// <returns>是否创建成功</returns>
private static bool CreateDWG(Solid3d solid3d, string strCableName)
{
     bool m_isSuccess = false;
     try
     {
         Document m_doc = Application.DocumentManager.Add(Global.InstallPath + @"\acad3D.dwt");
         Database m_db = m_doc.Database;
         using (DocumentLock docLock = m_doc.LockDocument())
         {
             using (Transaction tran = m_db.TransactionManager.StartTransaction())
             {
                 BlockTable bt = tran.GetObject(m_db.BlockTableId, OpenMode.ForRead) as BlockTable;
                 BlockTableRecord btr = tran.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                 btr.AppendEntity(solid3d);
                 tran.AddNewlyCreatedDBObject(solid3d, true);
                 tran.Commit();
             }
         }

         if (!File.Exists(Global.G_SavePath + "\\" + strCableName + ".dwg"))
         {
             m_doc.CloseAndSave(Global.G_SavePath + "\\" + strCableName + ".dwg");
         }
         else
         {
             File.Delete(Global.G_SavePath + "\\" + strCableName + ".dwg");
             m_doc.CloseAndSave(Global.G_SavePath + "\\" + strCableName + ".dwg");
         }
         m_isSuccess = true;
     }
     catch (CustomException ex)
     {
         Log.RecordExcetion(ex);
     }
     return m_isSuccess;
}