0

我正在尝试在 .dwg 文件中列出块属性并将它们保存在我的数据库中,这是我正在使用的代码:

using Autodesk.AutoCAD.DatabaseServices;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace CSP1257.Helpers
{
    public class AutocadHelper
    {

        public static Dictionary<string,string> ListAttributes(string dwgFile)
        {
            Dictionary<string, string> ret = new Dictionary<string, string>();

            using (Database attDb = new Database(false, true))
            {
                attDb.ReadDwgFile(dwgFile, FileShare.ReadWrite, false, null);
                Transaction tr = attDb.TransactionManager.StartTransaction();
                BlockTable bt = (BlockTable)attDb.BlockTableId.GetObject(OpenMode.ForRead);
                BlockTableRecord mBtr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);

                foreach (ObjectId msId in mBtr)
                {
                    BlockReference blkRef = (BlockReference)tr.GetObject(msId, OpenMode.ForRead);
                    AttributeCollection atts = blkRef.AttributeCollection;
                    if (atts == null)
                        continue;

                    foreach (ObjectId arId in atts)
                    {
                        AttributeReference attRef = (AttributeReference)tr.GetObject(arId, OpenMode.ForRead);
                        ret.Add(attRef.Tag, attRef.TextString);
                    }
                }
            }

            return ret;
        }
    }
}

但是我得到了这个例外:

Common Language Runtime detected an invalid program.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidProgramException: Common Language Runtime detected an invalid program.

Source Error:     
Line 20:                 Transaction tr = attDb.TransactionManager.StartTransaction();

我不确定为什么会出现此异常,是否有另一种方法可以达到相同的结果?

4

1 回答 1

-1

更新:

错误发生在演员表中,所以我们需要像这样检查:

 DBObject obj = tr.GetObject(msId, OpenMode.ForRead);

                if (obj.GetType() != typeof(BlockReference)) continue;

                BlockReference blkRef = obj as BlockReference;

我认为这是问题所在:BlockReference blkRef = (BlockReference)tr.GetObject(msId, OpenMode.ForRead);

您将模型空间中的每个对象都转换为一个块,但模型空间中也可能有一条线。然后在下一行中,您尝试获取一行的属性集合。这是不可能的。

所以解决方案是检查 BlkRef == null 在这种情况下是否跳过它。

if (BlkRef == null) continue;
于 2016-08-19T09:34:13.283 回答