Pasting a Grasshopper file in c# or ghPython

Hi there,

I was wondering whether someone has found a solution to programmatically pasting a grasshopper file ,using its file path, to the current canvas you are working in via GhPython or C#.

Let me know,

Hi @kdaw long time no see, hope you are doing well.

There is a method on GH_Document to merge in another doc, which can be used for that. See the attached example script.

import_gh_file.gh (3.5 KB)

You would probably want to extend the script to support a custom undo/redo flag, since this operation is not undoable by itself. Also I’m not sure how well this behaves with gh files that contain clusters, as they are conceptually like nested files.

# run is an input on the gh component
# path is an input on the gh component

import Grasshopper
import clr
clr.AddReference("GH_IO.dll")
import GH_IO as gio

def get_active_doc():
    canvas = Grasshopper.Instances.ActiveCanvas
    if canvas is None:
        return None
        
    return canvas.Document

def archive_to_doc(archive):
    """
    Convert a GH_Archive to a GH_Document
    """
    
    doc = Grasshopper.Kernel.GH_Document()
    if(not archive.ExtractObject(doc, "Definition")):
        return None
        
    return doc

def main():

    archive = gio.Serialization.GH_Archive()
    archive.ReadFromFile(path)

    if archive is None:
        print("Failed to read gh file at input path")
        return 

    doc = archive_to_doc(archive)
    if doc is None:
        print("Failed to create doc from input path")
        return
        
    active_doc = get_active_doc()
    if active_doc is None:
        print("Failed to retrieve active doc")
        return
        
    result = active_doc.MergeDocument(doc, True)
    if not result:
        print("Failed to insert other document")

if run:
    main()
2 Likes