Convert .gh file to .ghx in a grasshopper C# plugin

Hey guys.

I have created a new button in the grasshopper toolbar with is supposed to “save” the curreently open .gh file, export/convert it to .ghx and upload that to a server.

The only missing step is how can I convert the current file which is open in grasshopper to .ghx using C# code in my plugin?

Thanks,
Ricardo

The GH_DocumentIO class can be used to save a document to either gh or ghx file formats. Depending on the extension used when invoking the Save methods.

If you must generate the xml in memory, additional work is required, in fact I’m not even 100% sure it’s possible.

Here’s two ways.

  1. construct a new GH_DocumentIO with the document as a constructor argument. Then call SaveQuiet(“path.ghx”) on it. Finally harvest the bytes/text from the saved file.

  2. construct a ne GH_DocumentIO with the document as a constructor argument. Call Copy(GH_ClipboardType.Local) to serialise the document as an xml string. Then get that string using the LocalClipboardContent property. Do note however that the xml string used in clipboard operations differs somewhat from a ghx file. Maybe it doesn’t matter, maybe you can post-process the string…

    internal static string QuickSaveAsGhx(GH_ISerializable ghDoc)
    {
        GH_Archive archive = new GH_Archive();
        if (!archive.AppendObject(ghDoc, "Definition"))
            return null;
        else
            return archive.Serialize_Xml();
    }
1 Like