C# .net Make a function that takes in CSV and draw lines

C# .net Make a function that takes in CSV and draw lines

jeff.wangD95HG
Collaborator Collaborator
1,118 Views
10 Replies
Message 1 of 11

C# .net Make a function that takes in CSV and draw lines

jeff.wangD95HG
Collaborator
Collaborator

Hello I am fairly new to C# .net programming and I want write a program that  will read CSV that contains

X starting, Y starting, X ending, Y ending and draw lines out of those information.

Basically take the starting coordinate and draw a line to the ending coordinate

 

Any pointers on how to get started? I already have the environment setted up already

0 Likes
Accepted solutions (1)
1,119 Views
10 Replies
Replies (10)
Message 2 of 11

_gile
Consultant
Consultant

Hi,

In general, I recommend that anyone wanting to get started with C# should start by learning the basics of .NET C# programming outside AutoCAD before embarking on learning the AUtoCAD .NET API.
In your case, this is essential for certain tasks such as :
- reading a text file using a StreamReader instance (which will also give you an insight into the use of using statements).
- converting a character string containing data with a separator into a single-dimension array of strings using the String.Split method.
- parse a string representing a real number into a double using the double.Parse method.

 

Only once you've learned this can you use the data in AutoCAD to create lines.

- Start a new AutoCAD project

- Learn the basics of the AutoCAD API

- Create  AutoCAD entities



Gilles Chanteau
Programmation AutoCAD LISP/.NET
GileCAD
GitHub

Message 3 of 11

jeff.wangD95HG
Collaborator
Collaborator

I quickly gave my question to ChatGPT and this is what I got

 

 

using System;
using System.Collections.Generic;
using System.IO;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;


public class LineDrawingUtils
{
[CommandMethod("DrawLinesFromCSV")]
public void DrawLinesFromCSV()
{
// Get the CSV file path from user input
string csvFilePath = GetFilePath("Select CSV File", "CSV Files (*.csv)|*.csv");

if (!string.IsNullOrEmpty(csvFilePath))
{
try
{
// Read the CSV file and draw lines
DrawLinesFromCSVData(csvFilePath);
}
catch (Exception ex)
{
Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(ex.Message);
}
}
}

private string GetFilePath(string prompt, string filter)
{
PromptOpenFileOptions options = new PromptOpenFileOptions(prompt, filter);
PromptFileNameResult result = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetFileNameForOpen(options);
return result.Status == PromptStatus.OK ? result.StringResult : string.Empty;
}

private void DrawLinesFromCSVData(string csvFilePath)
{
if (!File.Exists(csvFilePath))
{
Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("CSV file not found.");
return;
}

using (Transaction transaction = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database.TransactionManager.StartTransaction())
{
using (StreamReader reader = new StreamReader(csvFilePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] data = line.Split(',');

if (data.Length == 4 &&
double.TryParse(data[0], out double startX) &&
double.TryParse(data[1], out double startY) &&
double.TryParse(data[2], out double endX) &&
double.TryParse(data[3], out double endY))
{
Point3d start = new Point3d(startX, startY, 0);
Point3d end = new Point3d(endX, endY, 0);

DrawLine(start, end);
}
}
}

transaction.Commit();
}
}

private void DrawLine(Point3d startPoint, Point3d endPoint)
{
using (Transaction transaction = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database.TransactionManager.StartTransaction())
{
BlockTable blockTable = transaction.GetObject(Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord modelSpace = transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

Line line = new Line(startPoint, endPoint);
modelSpace.AppendEntity(line);
transaction.AddNewlyCreatedDBObject(line, true);

transaction.Commit();
}
}
}

 

 

is that the correct syntax to read from file path?

0 Likes
Message 4 of 11

jeff.wangD95HG
Collaborator
Collaborator
using System;
using System.IO;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;

public class CsvLineDrawer
{
    public static void DrawLinesFromCsv(string csvFilePath)
    {
        if (!File.Exists(csvFilePath))
        {
            Console.WriteLine("CSV file not found.");
            return;
        }

        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 static 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();
        }
    }
}

 

generated it again today, but this time the functions are more familiar to me

0 Likes
Message 5 of 11

jeff.wangD95HG
Collaborator
Collaborator
Accepted solution

 

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.

 

0 Likes
Message 6 of 11

kerry_w_brown
Advisor
Advisor

@jeff.wangD95HG 

 

Can you please format the code by using the 'Insert/Edit code sample' button with language set to C#

 

Do you have a record of the questions you asked the AI for each response ??


// Called Kerry or kdub in my other life.

Everything will work just as you expect it to, unless your expectations are incorrect. ~ kdub
Sometimes the question is more important than the answer. ~ kdub

NZST UTC+12 : class keyThumper<T> : Lazy<T>;      another  Swamper
0 Likes
Message 7 of 11

jeff.wangD95HG
Collaborator
Collaborator

JULY 26

"write me a function in C# .net for civil 3d that reads CSV containing X start, Y start, X end, and Y end and draw a line according to those information"

 

regenerate response

 

"write me a function in C# .net for civil 3d that reads CSV containing X start, Y start, X end, and Y end and draw a line according to those information"

 

"make it so I can call the function from civil 3d"

 

each correspond to the code that was posted

 

I need some help on how to insert format option on this forums

0 Likes
Message 8 of 11

Ed__Jobe
Mentor
Mentor

@jeff.wangD95HG wrote:

I need some help on how to insert format option on this forums


To edit a post, click on the 3 vertical dots in the upper right of the post and select Edit Reply. Cut the code from the post. Click on the </> button to open the code window. If the button isn't visible, click on the three horizontal dots to show more command buttons. Paste the code into the code window. Select C# as the language format and click OK.

Ed


Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.
How to post your code.

EESignature

0 Likes
Message 9 of 11

_gile
Consultant
Consultant

@jeff.wangD95HG  a écrit :

I quickly gave my question to ChatGPT and this is what I got


IMHO, if you want to learn AutoCAD programming keep far away from ChatGPT (or any other chatbot) and write code by yourself.



Gilles Chanteau
Programmation AutoCAD LISP/.NET
GileCAD
GitHub

0 Likes
Message 10 of 11

jeff.wangD95HG
Collaborator
Collaborator

Well I think this is like having answers at the back of the text book.

I don't think its worthwhile banging your head without any ideas of what the answers look like. If you know seen enough examples and reversed engineered enough solutions you should get better. But if you just copied the answers to the back of the text book without doing any additional work, of course you are not going to learn anything.

 

I already have a good basic understanding of coding in python and C++ I am just not aware of the syntax and tools that are available to use in C# and civil api

0 Likes
Message 11 of 11

kerry_w_brown
Advisor
Advisor

>>> Well I think this is like having answers at the back of the text book.

 

No, not really.

It's more like getting someone else to do your homework.

 

If it was the back of the textbook you could be more comfortable that the answer may be correct.

 

but, to each his own  🙂

 

 


// Called Kerry or kdub in my other life.

Everything will work just as you expect it to, unless your expectations are incorrect. ~ kdub
Sometimes the question is more important than the answer. ~ kdub

NZST UTC+12 : class keyThumper<T> : Lazy<T>;      another  Swamper