Adding a block from another file

Ok. I made it finally
Here is a code sample in case anyone needs it.

private void RunScript(string filePath, string blockName)
{

    int index = -1; //instance definition index

    //check if block exists in current file;
    var localDef = RhinoDocument.InstanceDefinitions.Find(blockName);

    if (localDef != null)
    {
      index = localDef.Index;
    }
    else //get block from the outer file
    {
      var refDoc = Rhino.FileIO.File3dm.Read(filePath);

      var instDefs = refDoc.AllInstanceDefinitions;

      //find the blocks needed
      var instDef = instDefs.Where(d => d.Name == blockName).FirstOrDefault();

      if (instDef != null)
      {
        //add layers to current document otherwise imported blocks will loose layers/color
        var refLayers = refDoc.AllLayers;
        foreach (var layer in refLayers)
        {
          RhinoDocument.Layers.Add(layer);
        }

        //find block Objects
        var refObjects = refDoc.Objects;
        var ids = instDef.GetObjectIds();
        var objs = ids.Select(id => refObjects.FindId(id));

        //Add Instance Definition to the current file
        index = RhinoDocument.InstanceDefinitions.Add(blockName, string.Empty, Point3d.Origin, objs.Select(o => o.Geometry), objs.Select(o => o.Attributes));
      }
    }

    //Place new block to the document
    var xform = Transform.Identity;
    RhinoDocument.Objects.AddInstanceObject(index, xform);

}

6 Likes