Here’s a way to store ‘global’ data in the *.gh file, but it is only available during Write() and Read() processes. Still, during runtime you can have your own data class running which associates with specific documents.
The component below will create a new chunk in the gh file and store some data in it:
using System;
using System.Windows.Forms;
using GH_IO.Serialization;
using Grasshopper.Kernel;
namespace IoHackComponents
{
public sealed class IoHackComponent : GH_Component
{
public IoHackComponent()
: base("IO hacking test", "IOHack", "Test for reading and writing data into a GH file.", "IO", "Test")
{
FileData = null;
}
public override Guid ComponentGuid => new Guid("{0A9FAE7F-541B-4B34-90CC-C1AE3382CB57}");
protected override void RegisterInputParams(GH_InputParamManager pManager) { }
protected override void RegisterOutputParams(GH_OutputParamManager pManager)
{
pManager.AddTextParameter("Data", "D", "Data stored in file.", GH_ParamAccess.item);
}
protected override void SolveInstance(IGH_DataAccess access)
{
access.SetData(0, FileData);
}
public string FileData { get; set; }
protected override void AppendAdditionalComponentMenuItems(ToolStripDropDown menu)
{
Menu_AppendItem(menu, "Set File Data", SetFileDataClick);
}
private void SetFileDataClick(object sender, EventArgs eventArgs)
{
if (Rhino.UI.Dialogs.ShowEditBox(
"Global File Data",
"Edit the global file data.",
FileData,
true,
out string newFileData))
{
if (string.Equals(FileData, newFileData))
return;
FileData = newFileData;
ExpireSolution(true);
}
}
#region IO hacking
private const string GlobalChunkName = "GlobalFileData";
private const string GlobalValueName = "GlobalString";
public override bool Write(GH_IWriter writer)
{
if (FileData != null)
if (writer is GH_Chunk chunk)
{
var root = chunk.Archive.GetRootNode;
if (root.FindChunk(GlobalChunkName) == null)
{
var globalChunk = chunk.Archive.GetRootNode.CreateChunk(GlobalChunkName);
globalChunk.SetString(GlobalValueName, FileData);
}
}
return base.Write(writer);
}
public override bool Read(GH_IReader reader)
{
FileData = null;
if (reader is GH_Chunk chunk)
{
var globalChunk = chunk.Archive.GetRootNode.FindChunk(GlobalChunkName);
if (globalChunk != null)
FileData = globalChunk.GetString(GlobalValueName);
}
return base.Read(reader);
}
#endregion
}
}
