Access Drawing database without Opening it then Create Objects Inside then Save

Access Drawing database without Opening it then Create Objects Inside then Save

john-malulan
Participant Participant
2,460 Views
3 Replies
Message 1 of 4

Access Drawing database without Opening it then Create Objects Inside then Save

john-malulan
Participant
Participant

Good day Everyone. I'm new to AutoCAD C# Programming asking for your kind assistance. 

 

What I'm trying to do is

1. Access Drawing Database without Opening it in the Editor ( Template Drawing )

2. Create Objects Inside It 

3. Assign Layer Property to the Created Objects

4. Save as New Drawing  ( Output Drawing ) 

 

I followed this Solution and It works, I can already Access the drawing database and Create Objects Inside it and then save into a different drawing. 

https://forums.autodesk.com/t5/net/how-to-open-an-autocad-file-update-and-close-with-save-using-c/td...

 

But when I try to assign a layer property in the new object I get eKeyNotFound Error even though the Template drawing that I access has that layer. 

 

I also followed this Link but still no Luck. 

https://forums.autodesk.com/t5/net/how-change-layer-of-specific-entity/td-p/8577610

 

Here is my Source Code. 

 

[CommandMethod("CHANGENEW")]
public static void CreateText()
{
    //Get the template plant database
    Database acCurDb = new Database(false, true);
    string dwgFlpath = @"D:\Users\johnrey.d.malulan\Downloads\Hotaka_New_Type_Test.dwg";

    //Set the output Drawing Directory
    Document acDoc = Application.DocumentManager.MdiActiveDocument;
    string strDWGName = acDoc.Name;
    strDWGName = @"D:\Users\johnrey.d.malulan\Downloads\Output.dwg";


    acCurDb.ReadDwgFile(dwgFlpath, FileOpenMode.OpenForReadAndAllShare, false, null);




    // Start a transaction
    using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
    {
        // Open the Block table for read
        BlockTable acBlkTbl;
        acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                           OpenMode.ForRead) as BlockTable;
        // Open the Block table record Model space for write
        BlockTableRecord acBlkTblRec;
        acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
                                              OpenMode.ForWrite) as BlockTableRecord;

        var layerName = "Character";
        // check if the layer already exists
        var lt = (LayerTable)acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead);
        if (!lt.Has(layerName))
        {
            // if not create it
            var layer = new LayerTableRecord()
            {
                Name = layerName,
                Color = Color.FromRgb(200, 30, 80)
            };
            lt.UpgradeOpen();
            lt.Add(layer);
            acTrans.AddNewlyCreatedDBObject(layer, true);
            Application.ShowAlertDialog("Layer Created");
        }


        // Create a single-line text object
        DBText acText = new DBText();
        //acText.SetDatabaseDefaults();
        acText.Position = new Point3d(2, 2, 0);
        acText.Layer = layerName;
        acText.Height = 500;
        acText.TextString = "Hello, World.";
        acBlkTblRec.AppendEntity(acText);
        acTrans.AddNewlyCreatedDBObject(acText, true);
        // Save the changes and dispose of the transaction
        acTrans.Commit();
    }
    acCurDb.SaveAs(strDWGName, DwgVersion.Current);
}

 

Please help me 😞 

0 Likes
Accepted solutions (1)
2,461 Views
3 Replies
Replies (3)
Message 2 of 4

_gile
Consultant
Consultant
Accepted solution

Hi,

You should use the LayerId property instead.

        public static void CreateFileWithText(string templatePath, string outputDwgPath)
        {
            // create a new Database (within a using statement to ensure the Database to be disposed)
            using (var db = new Database(false, true))
            {
                // read the template dwg file
                db.ReadDwgFile(templatePath, FileOpenMode.OpenForReadAndAllShare, false, null);

                // start a transaction
                using (var tr = db.TransactionManager.StartTransaction())
                {
                    // check if a layer named "Character" already exists and create it if not
                    string layerName = "Character";
                    ObjectId layerId;
                    var layerTable = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
                    if (layerTable.Has(layerName))
                    {
                        layerId = layerTable[layerName];
                    }
                    else
                    {
                        tr.GetObject(db.LayerTableId, OpenMode.ForWrite);
                        var layer = new LayerTableRecord
                        {
                            Name = layerName,
                            Color = Color.FromRgb(200, 30, 80)
                        };
                        layerId = layerTable.Add(layer);
                        tr.AddNewlyCreatedDBObject(layer, true);
                    }

                    // get the Model space
                    var modelSpace = (BlockTableRecord)tr.GetObject(
                        SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite);

                    // create a text
                    var text = new DBText
                    {
                        Position = new Point3d(2.0, 2.0, 0.0),
                        LayerId = layerId,
                        Height = 500.0,
                        TextString = "Hello, World."
                    };
                    modelSpace.AppendEntity(text);
                    tr.AddNewlyCreatedDBObject(text, true);

                    // save changes to the database
                    tr.Commit();
                }

                // save the new drawing
                db.SaveAs(outputDwgPath, DwgVersion.Current);
            }
        }

 

 



Gilles Chanteau
Programmation AutoCAD LISP/.NET
GileCAD
GitHub

Message 3 of 4

Alexander.Rivilis
Mentor
Mentor

Change:

 

 

acText.Layer = layerName;

 

 

with:

 

 

acText.LayerId = layerId; // ObjectId of your layer

 

 

P.S.: Oops! I did not see the @_gile answer.

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

Message 4 of 4

john-malulan
Participant
Participant
You're a life saver Sir, Thank you so much. Have a nice day!
0 Likes