using System;
using System.IO;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
public class CsvLineDrawer
{
[CommandMethod("DrawLinesFromCsv")]
public void DrawLinesFromCsv()
{
// Get the CSV file path from the user using AutoCAD file dialog
string csvFilePath = GetCsvFilePath();
if (!string.IsNullOrEmpty(csvFilePath))
{
if (!File.Exists(csvFilePath))
{
Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("CSV file not found.");
}
else
{
ProcessCsvFile(csvFilePath);
}
}
}
private string GetCsvFilePath()
{
// Use AutoCAD's file dialog to select the CSV file
Editor editor = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
PromptOpenFileOptions openOptions = new PromptOpenFileOptions("Select CSV File");
openOptions.Filter = "CSV Files (*.csv)|*.csv";
PromptFileNameResult result = editor.GetFileNameForOpen(openOptions);
if (result.Status == PromptStatus.OK)
{
return result.StringResult;
}
return null;
}
private void ProcessCsvFile(string csvFilePath)
{
using (var reader = new StreamReader(csvFilePath))
{
while (!reader.EndOfStream)
{
var lineData = reader.ReadLine();
var values = lineData.Split(',');
if (values.Length == 4 &&
double.TryParse(values[0], out double xStart) &&
double.TryParse(values[1], out double yStart) &&
double.TryParse(values[2], out double xEnd) &&
double.TryParse(values[3], out double yEnd))
{
DrawLine(xStart, yStart, xEnd, yEnd);
}
}
}
}
private void DrawLine(double xStart, double yStart, double xEnd, double yEnd)
{
Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor editor = doc.Editor;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
Point3d startPoint = new Point3d(xStart, yStart, 0);
Point3d endPoint = new Point3d(xEnd, yEnd, 0);
using (Line line = new Line(startPoint, endPoint))
{
btr.AppendEntity(line);
tr.AddNewlyCreatedDBObject(line, true);
}
tr.Commit();
}
}
}
ok several back and forth with chat GPT and this end up being the result.
works great in the first few attempts. But still require further testing.