Here's the EScript version of your AutoLISP code that imports attributes from a CSV file into all instances of a specified block:
using System;
using System.Collections.Generic;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
public class Commands
{
[CommandMethod("ImportBlockAtts")]
public void ImportBlockAtts()
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
Database db = HostApplicationServices.WorkingDatabase;
// Select a block reference
PromptEntityResult sel = ed.GetEntity("Select block instance to import attributes into all instances: ");
if (sel.Status != PromptStatus.OK)
return;
DBObject ent = sel.ObjectId.GetObject(OpenMode.ForRead);
if (ent == null || !(ent is BlockReference blkRef))
{
ed.WriteMessage("Selected object is not a block reference.");
return;
}
string blockName = blkRef.BlockTableRecord.Name;
// Collect all instances of this block
List<BlockReference> blockRefs = new List<BlockReference>();
using (Transaction tr = db.TransactionManager.StartTransaction())
{
BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
foreach (ObjectId btRecId in bt)
{
BlockTableRecord btr = tr.GetObject(btRecId, OpenMode.ForRead) as BlockTableRecord;
if (btr == null) continue;
foreach (ObjectId objId in btr)
{
Entity ent = tr.GetObject(objId, OpenMode.ForRead) as Entity;
if (ent is BlockReference br && br.BlockTableRecord.Name == blockName)
{
blockRefs.Add(br);
}
}
}
tr.Commit();
}
// Get CSV file path
string csvPath = ed.GetFileName("Select CSV file containing attributes", "*.csv|*.csv", "csv");
if (string.IsNullOrEmpty(csvPath))
return;
// Read CSV into dictionary
Dictionary<string, string> attributes = new Dictionary<string, string>();
try
{
using (StreamReader sr = new StreamReader(csvPath))
{
string line = sr.ReadLine(); // Skip header
while ((line = sr.ReadLine()) != null)
{
string[] parts = line.Split(',');
if (parts.Length < 2) continue;
string tag = parts[0].Trim();
string val = parts[1].Trim();
attributes[tag] = val;
}
}
}
catch (Exception ex)
{
ed.WriteMessage($"Error reading CSV: {ex.Message}");
return;
}
// Update each block instance's attributes
foreach (BlockReference br in blockRefs)
{
using (Transaction tr = br.Database.TransactionManager.StartTransaction())
{
br.UpgradeOpen();
foreach (ObjectId attId in br.GetAttributes())
{
AttributeReference attRef = tr.GetObject(attId, OpenMode.ForWrite) as AttributeReference;
if (attRef != null)
{
string tag = attRef.Tag;
if (attributes.TryGetValue(tag, out string value))
{
attRef.TextString = value;
}
}
}
tr.Commit();
}
}
ed.WriteMessage($"\nImported {attributes.Count} attributes into {blockRefs.Count} block instances.");
}
}