MicroStation Python: Open DGN File and Attach Reference


 

Welcome to the world of MicroStation Python! In this wiki, we'll explore how to open a DGN file and attach a reference DGN file.

 

Open DGN File and Attach Reference

To get started, refer to the Python Editor wiki for instructions on creating and loading a new Python project. Name your project "OpenDgnAndReferenceAttach.py" and save it in a convenient location. Once created, open the project in your preferred code editor to begin writing your Python script.

 

Here is the complete script.

 

from MSPyBentley import *
from MSPyECObjects import *
from MSPyBentleyGeom import *
from MSPyDgnPlatform import *
from MSPyDgnView import *
from MSPyMstnPlatform import *

import os
import sys


def attach_dgn_file(file_path, model_name, logical_name, scale):
    """
    Attaches a DGN file as a reference attachment to the active DGN model.
    """
    ACTIVEMODEL = ISessionMgr.ActiveDgnModelRef
    if ACTIVEMODEL is None:
        print("No active DGN model found.")
        return

    moniker = DgnDocumentMoniker.CreateFromFileName(file_path)
    if moniker is None:
        print("Failed to create moniker from file path.")
        return

    ret = ACTIVEMODEL.CreateDgnAttachment(moniker, model_name, True)
    if BentleyStatus.eSUCCESS != ret[0]:
        print("Failed to create DGN attachment.")
        return

    attachment = ret[1]
    attachment.SetLogicalName(logical_name)
    attachment.SetStoredScale(scale)

    if BentleyStatus.eSUCCESS != attachment.WriteToModel():
        print("Failed to write attachment to model.")
        return

    print("Reference DGN file attached successfully.")


def open_dgn_file(full_path):
    """
    Open a DGN file given a full path.
    The file is opened read/write if possible.
    """
    if not os.path.isfile(full_path):
        print(f"Error: File does not exist: {full_path}")
        return None

    # Create a DgnDocument for the local file
    doc = DgnDocument.CreateForLocalFile(full_path)
    if doc is None:
        print("Error: Failed to create DgnDocument for file.")
        return None

    # Create a DgnFile in read/write mode
    dgn_file = DgnFile(doc, DgnFileOpenMode.eReadWrite)

    # Load the DGN file
    status, fileOpenStatus = dgn_file.LoadDgnFile()

    print(f"LoadDgnFile status: {status}, fileOpenStatus: {fileOpenStatus}")

    if status != DgnFileStatus.eDGNFILE_STATUS_Success:
        print(f"Error: LoadDgnFile failed with status {status}")
        return None

    # Fill dictionary model (recommended after load)
    dgn_file.FillDictionaryModel()

    # Switch MicroStation session to this file
    sess_status = ISessionMgr.GetManager().SwitchToNewFile(
        doc,
        "",                             # inoutModelName
        GraphicsFileType.eGRAPHICSFILE_WildCard,
        True,                           # doUpdate
        True,                           # releaseReferences
        False,                          # reopeningAfterSave
        False                           # runInitUCM
    )
    
    if sess_status != DgnFileStatus.eDGNFILE_STATUS_Success:
        print(f"Warning: SwitchToNewFile failed with status {sess_status}")

    print(f"Successfully opened DGN file: {dgn_file.GetFileName()}")
    return dgn_file


def main():
    # Open a DGN file
    full_path = r"D:\BDN\Cases\2026\RefAtt\A.dgn"

    dgn_file = open_dgn_file(full_path)
    if dgn_file is None:
        # Non‑zero exit code for error
        sys.exit(1)

    # At this point dgn_file is loaded and ready for further operations.
    # For example, get default model:
    model_id = dgn_file.GetDefaultModelId()
    status, dgn_model = dgn_file.LoadRootModelById(model_id, True, True)
    if status != BentleyStatus.eSUCCESS:
        print("Error: Failed to load default model from file.")
        sys.exit(1)

    print(f"Default model name: {dgn_model.GetModelName()}")

    # Reference attach DGN file to the active model
    ref_file_name = r"D:\BDN\Cases\2026\RefAtt\B.dgn"
    attach_dgn_file(ref_file_name, "3D Metric Design", "My Reference B", 1.0)


if __name__ == "__main__":
    main()

 

Run/Execute project

Load the project "OpenDgnAndReferenceAttach.py" from the Python Editor dialog and Run/Execute the python script.

A DGN file is open and loaded in the active session. Once the file is loaded, a reference file is attached.

 

 

Python: Documentation | API Presentations | FAQs | GitHub | Samples | Wikis | Blogs