Automating AutoCAD Map 3D: Scripts, AutoLISP and the .NET API

Automating AutoCAD Map 3D: Scripts, AutoLISP and the .NET API

Every CAD manager I know has a story about a routine that got out of hand. Mine is about a small AutoLISP program, written in the late nineties by a long-departed colleague, that lived in a shared folder called “TOOLS_OLD” and was loaded by the startup file of every machine in the office. Its job was to “tidy the layers.” Nobody knew exactly what that meant. It had survived three software upgrades, two office moves and one entire change of drawing standard, and one Thursday afternoon, after an unrelated update, it began quietly deleting layers whose names contained a hyphen. Which, under the new standard, was every layer in the building. We found out because a drawing set went to the client with the base map missing.

I tell that story first because it contains the whole philosophy of this guide. Automation is the most powerful thing a CAD manager does, and the most dangerous. A good routine saves thousands of hours and makes the office more consistent than any manual could. A bad one, or a forgotten one, destroys data at the speed of a computer. The difference is not talent. It is discipline: knowing what to automate, choosing the right level of tool, writing code that fails safely, testing on copies, deploying under control and retiring what is no longer needed.

In this guide I’ll cover the whole ladder of automation available in AutoCAD Map 3D (and the AutoCAD platform beneath it): from script files and the command line, through AutoLISP, to the .NET API, and the outside world of Python and external tools. I’ll show examples at each level, say when each is the right choice, explain how to deploy and govern the code, and give you the list of automations that, in my experience, pay back fastest. It is part of our Autodesk series. For the program, see AutoCAD Map 3D Beginner’s Guide, and for running automation across hundreds of drawings, Batch Processing DWG Files: Core Console, Scripts and FME.

A note on facts: AutoCAD and Map 3D APIs change between versions (for example, the .NET runtime that the program uses has changed over the years), and I cannot test Autodesk code in this environment. The examples are illustrative patterns based on widely used, long-standing interfaces. Test every routine on copies, in your own version, and check the Autodesk API documentation for exact names and behavior.

Chart: Scripts, AutoLISP and the .NET API trade off effort against power.
Scripts, AutoLISP and the .NET API trade off effort against power.

The Automation Ladder

Think of automation as a ladder, and climb only as high as the job needs.

RungToolSkills neededBest forMain risk
1Aliases, tool palettes, templates, saved profilesNoneEveryday speed, standardsHard to share if not centralized
2Script files (.scr)Know the commandsRepeating the same command sequence, simple batch workFragile if prompts change
3Action recorder and macrosLittleRecording a task and replaying itRecorded actions can be brittle
4AutoLISP and Visual LISPSome programmingQuick routines, checks, selection and editing, small toolsOld code with no owner
5.NET API (C# or VB.NET)ProgrammingRobust, fast, structured tools, user interfaces, integrationNeeds development discipline and recompiling for new versions
6C++ (ObjectARX)AdvancedVery deep integration, performanceSpecialist skill, heavy maintenance
7External programs (Python, scheduled tasks, server tools)ProgrammingReading and writing drawings outside the application, pipelinesLimited access to live application features

A principle I teach: climb the ladder one rung at a time, and stop as soon as the job is done. A five-line script file is better than a five-hundred-line plugin, if it does the same job.


Rung 1: Standards Before Code

Before writing any code, fix the environment, because most of what people try to automate is a symptom of a missing standard.

If the template and standards are right, half of the tasks that tempt people to write code disappear.


Rung 2: Script Files

A script file is a plain text file where each line is something you would have typed at the command line. AutoCAD runs it with the SCRIPT command. Because it is just text, it is easy to write, easy to read and easy to generate.

The rules

  • Each line is one input, and an empty line acts like pressing Enter.
  • Use command-line versions of commands, which usually start with a hyphen (for example -LAYER and -PURGE), so that they don’t open dialog windows.
  • Use the underscore and period prefix (_.) so the script works in any language version, and with redefined commands.
  • System variables such as FILEDIA and CMDDIA control whether dialogs open. Scripts may need them set to 0.
  • Scripts can’t branch or loop by themselves. They run straight through.

A cleanup script

_.AUDIT
_Y
_.-PURGE
_A
*
_N
_.ZOOM
_E
_.QSAVE

This audits the drawing (fixing errors), purges all unused named objects, zooms to the extents and saves. (The exact prompts of -PURGE and other commands vary slightly between versions, so run the script by hand on a test drawing and watch the command line.) For the background, see Corrupted or Bloated DWG Files: Audit, Recover and Purge.

Generating scripts for many drawings

Scripts are text, so a program can write them. A short Python helper that creates one script per drawing, with the drawing’s name inserted:

from pathlib import Path

TEMPLATE = """_.AUDIT
_Y
_.-PURGE
_A
*
_N
_.SAVEAS
2018
{out_path}
_.QUIT
"""

def make_script(dwg_path, out_dir):
    dwg = Path(dwg_path)
    out_dwg = Path(out_dir) / dwg.name
    script_path = Path(out_dir) / (dwg.stem + ".scr")
    script_path.write_text(TEMPLATE.format(out_path=str(out_dwg)), encoding="ascii", errors="replace")
    return script_path

print(make_script("projects/pump_station.dwg", "cleaned"))

Check the prompts of SAVEAS in your version before relying on a template like this, and test with a handful of drawings. The article on batch processing shows how to run such scripts across hundreds of files without opening each one on screen.

When a script is the right tool

  • A fixed sequence of commands.
  • No decisions based on the drawing’s content.
  • Batch jobs on many drawings.
  • Quick wins that you can build in an hour.

When it is not

  • When you need to look at the data and decide (which layer? which objects?).
  • When prompts change with the content.
  • When error handling matters.

Rung 3: The Action Recorder

AutoCAD’s action recorder records the commands and inputs you perform, and saves them as a macro. It is a gentle way for a non-programmer to automate a repeated task, and a useful starting point for a script. Recorded macros inherit the brittleness of the prompts they record, and they have limited flexibility. Use them for simple tasks, and expect to rebuild them when a command changes.


Rung 4: AutoLISP

AutoLISP is the veteran of AutoCAD automation. It is a dialect of the LISP language, built into AutoCAD, and it can run commands, read and modify drawing objects, access the drawing database and system variables, and prompt the user. Visual LISP adds an editor, a debugger and functions to work with AutoCAD’s object model (the vl- and vla- function families).

Why it endures

  • It is built in: no installation, no compilation.
  • It is quick to write for small jobs.
  • A huge body of examples exists.
  • It works with the drawing database directly: layers, blocks, text, entities.
  • Load-on-demand and automatic loading are easy.

The limits

  • Old and idiosyncratic syntax, which fewer people know.
  • Limited structure for large programs.
  • Weaker tooling than modern languages: testing and version control take discipline.
  • No access to some modern features that the .NET API exposes more fully.
  • A source of orphaned code, like my “TOOLS_OLD” routine.

Example 1: list the non-standard layers

A routine a CAD manager can use daily. It walks the layer table and reports any layer that is not in the standard list.

(defun c:CHKLAYERS ( / std rec name bad)
  ;; Standard layer names in upper case. Replace with your office standard.
  (setq std '("0" "WM-PIPE" "WM-VALVE" "WM-TEXT" "ROAD" "PARCEL")
        rec (tblnext "LAYER" T)
        bad nil)
  (while rec
    (setq name (cdr (assoc 2 rec)))
    (if (not (member (strcase name) std))
      (setq bad (cons name bad)))
    (setq rec (tblnext "LAYER")))
  (if bad
    (progn
      (princ "\nNon-standard layers:")
      (foreach n (reverse bad) (princ (strcat "\n  " n))))
    (princ "\nAll layers conform."))
  (princ))

Type CHKLAYERS at the command line after loading it. (Layers from external references contain a vertical bar in their names, and may appear in the report. Filter them if you wish.)

Example 2: count text objects outside the standard heights

This one checks the annotation standard from Annotation, Scales and Plot Standards: From CAD Drawings to Professional Maps, for a drawing at 1:500 with model units in meters, where the standard heights are 1.25, 1.75 and 2.5 meters.

(vl-load-com)
(defun c:CHKTEXT ( / ss i ent h bad total)
  (setq ss (ssget "X" '((0 . "TEXT"))) bad 0 total 0)
  (if ss
    (repeat (setq i (sslength ss))
      (setq ent (ssname ss (setq i (1- i)))
            h (cdr (assoc 40 (entget ent)))
            total (1+ total))
      (if (not (vl-some '(lambda (a) (< (abs (- h a)) 0.001)) '(1.25 1.75 2.5)))
        (setq bad (1+ bad)))))
  (princ (strcat "\nText objects checked: " (itoa total)
                 ". Outside standard heights: " (itoa bad) "."))
  (princ))

Make the list of heights depend on the drawing’s scale, and extend the routine to select the offenders so that they can be fixed. Keep the routine read-only by default.

Safe habits for AutoLISP

  • Wrap changes in an undo group so that a user can reverse them with one command:
(command "_.UNDO" "_BEGIN")
;; ... make the changes ...
(command "_.UNDO" "_END")
  • Save and restore system variables (such as OSMODE, CMDECHO, ATTREQ) that your routine changes, and restore them even if an error occurs, using an error handler.
  • Report what you did, in the command line, counts and names.
  • Prefer reading to writing until the routine is proven.
  • Avoid hard-coded paths and machine-specific assumptions.
  • Comment the purpose, the author and the date at the top of every file.
  • Test on a copy of a drawing, and on a drawing with unusual content.

Map 3D and AutoLISP

Map 3D adds AutoLISP functions for working with object data, queries and other Map features (the function names typically begin with a recognizable prefix, so look them up in the Map 3D developer documentation). With them, you can read or write object data on objects, list tables and fields, and automate repetitive attribute tasks. See Object Data, Object Classes and Attributes in AutoCAD Map 3D. Check the documentation for exact function names and for what your version supports.

Loading and deploying AutoLISP

  • Startup files: acad.lsp and acaddoc.lsp load routines when AutoCAD or a drawing opens.
  • The Application Load tool (APPLOAD) and its Startup Suite load files for the user.
  • Support file search paths locate the files centrally.
  • Trusted locations: AutoCAD restricts where code can run from, and the settings (TRUSTEDPATHS, SECURELOAD) matter. Put your tools in a controlled, trusted, read-only network location.
  • Compiled (FAS or VLX) files hide source code. If you use them, keep the source in version control.

Rung 5: The .NET API

For anything larger than a small routine, the .NET API is the professional choice. You write a class library in C# or VB.NET, referencing AutoCAD’s managed assemblies, and load it into the program. (The .NET runtime that AutoCAD uses has changed with newer releases, so the project settings depend on your version. Check Autodesk’s developer documentation.)

What it gives you

  • A structured language with strong tooling: an editor, a debugger, unit tests, version control and package management.
  • Full access to the drawing database and the editor, with transactions that make changes safe.
  • Custom commands, dialogs, palettes and ribbon items.
  • Speed, for processing large drawings.
  • Reuse of the wider .NET ecosystem: databases, web services, spreadsheets, JSON.
  • Map 3D’s own APIs: the Map .NET API exposes object data, coordinate systems, queries and other Map functions, and the FDO API handles connections to data sources. Check the documentation for your version.

A minimal command

The classic structure: a command method that opens a transaction, reads objects and commits.

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

[assembly: CommandClass(typeof(OfficeTools.Commands))]

namespace OfficeTools
{
    public class Commands
    {
        [CommandMethod("COUNTBYLAYER")]
        public void CountByLayer()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            var counts = new Dictionary<string, int>();

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);

                foreach (ObjectId id in ms)
                {
                    Entity ent = (Entity)tr.GetObject(id, OpenMode.ForRead);
                    counts[ent.Layer] = counts.TryGetValue(ent.Layer, out int n) ? n + 1 : 1;
                }
                tr.Commit();
            }

            foreach (var kv in counts)
                ed.WriteMessage($"\n{kv.Key}: {kv.Value}");
        }
    }
}

After building the assembly, load it with the NETLOAD command and type COUNTBYLAYER. The structure is the same for far larger tools: open a transaction, get objects, read or modify them, commit. Always open objects for read unless you need to write, and always handle exceptions.

Why a CAD manager might choose .NET

The cost

  • Development discipline: source control, code review, testing and documentation.
  • Compatibility: the API changes with Autodesk releases, so you may need to recompile and retest your tools for each version.
  • Deployment and security: distribution, trust settings and code signing.
  • Support: someone has to own the code for years.

Civil 3D and other products

Civil 3D has its own .NET API, with objects for alignments, surfaces, parcels and pipe networks. See Dynamo and the Civil 3D API for Automation.


Rung 7: Outside the Application

Not everything needs to run inside AutoCAD.

These are particularly useful for QA reports across an archive, where opening each drawing is slow and unnecessary.


Choosing the Right Rung

TaskGood choiceWhy
Purge, audit and save a hundred drawingsScript file, run in batchFixed sequence, no decisions
Check layers and text heights, report exceptionsAutoLISP, or Python on DXFQuick and read-only
Update title blocks from a spreadsheetAutoLISP or .NETNeeds access to attributes
A tool with a dialog for editors.NETUser interface and reliability
Export object data across an archive to a database.NET (with the Map API) or FMEStructured data access
Convert an archive to GIS formatsFME or GDALBuilt for conversion
Generate a web viewer of drawingsCloud APIsWeb delivery
Recurring office standard checksCAD standards files, plus a scriptUse the built-in checker where it exists

The CAD Manager’s Rules for Automation

These came from scars.

  1. Don’t automate a broken process. Fix the standard first.
  2. Know the owner. Every tool has a named owner, a purpose and a date. If the owner leaves, the tool is reassigned or retired.
  3. Keep source in version control, even for LISP. The “TOOLS_OLD” routine had no source, only the loaded file.
  4. Never run new code on the only copy of a drawing.
  5. Make tools read-only by default, with a clear report, and add a “fix” option only after the report is trusted.
  6. Log everything that changes data: what, where, when, by whom.
  7. Use undo groups and restore system variables.
  8. Test in a staging environment, with sample drawings that include unusual content: xrefs, proxies, old versions, missing fonts, large files.
  9. Version the tools and the drawing standard together, and record which version of the tool matches which version of the standard.
  10. Document in plain language: what it does, how to run it, what it changes, what to do if it fails.
  11. Deploy from one controlled location, in a trusted path, and not from copies on individual machines.
  12. Review annually, and retire tools that new software features have replaced.
  13. Train the users in what the tool does, not only which button to press.
  14. Watch for version changes: test your tools on each new release before the office upgrades.
  15. Secure it: sign code where you can, restrict who may change the tool folders, and review third-party tools before adding them.

The Automations That Pay Back Fastest

If you are looking for a place to begin, this is my short list, in the order I’d tackle them.

  1. Standards checking: layers, text styles, dimension styles, line types, against the office standard. Report first, fix later.
  2. Purge, audit and save, as a batch routine for finished drawings.
  3. Title block and revision updates from project data.
  4. Plot and publish with standard page setups, as a controlled routine. See Mapping and Plotting in AutoCAD Map 3D: Styles, Thematic Maps and Map Book.
  5. External reference path repair, for the endless moves of project folders. See Civil 3D Data Shortcuts and Xref Problems.
  6. Coordinate system checks: does every drawing have an assigned system, and is it the project’s? See Coordinate Systems in AutoCAD Map 3D and Civil 3D Explained.
  7. Object data audits: missing fields, invalid values, duplicates. See Object Data, Object Classes and Attributes in AutoCAD Map 3D.
  8. Export to GIS through saved Map profiles or FME, with a validation report. See Importing and Exporting GIS Data in AutoCAD Map 3D.
  9. Data extraction: block attributes and object data to tables.
  10. Archive reports: a nightly summary of drawing sizes, versions and warnings.

A Worked Example: A Standards Audit Tool for the Whole Office

Task: my office needed to check every drawing leaving a project against the layer and text standards, without people having to remember.

  1. Specify the checks: layers must be on the standard list (with project-specific additions allowed by a pattern), text heights must match the table for the layout’s scale, no objects on layer 0 except blocks, a coordinate system must be assigned, and the drawing must have no unreferenced xrefs.
  2. Prototype in Python on DXF exports of 20 sample drawings, with ezdxf, to refine the rules and the report format, since it is fast to change.
  3. Port the stable checks to AutoLISP for the interactive “check my drawing” command, which reports on the command line and writes a short text file next to the drawing.
  4. Build the batch version as a script run in the Core Console, producing a CSV of results per drawing, for project managers.
  5. Pilot: run on 200 recent drawings. The most common findings: non-standard layers from imported consultant files (45 percent), text at non-standard heights (30 percent), missing coordinate systems (12 percent).
  6. Review with the users: the first version was too noisy, flagging legitimate exceptions. Add an exceptions file per project, controlled by the project manager.
  7. Deploy: from a single trusted network location, with the version number in the command’s output and a one-page how-to.
  8. Govern: the tool has an owner, a change log, and a source repository. Changes to the standard trigger changes to the tool, and the reverse.
  9. Measure: within three months, the share of drawings failing the check at issue dropped from 38 percent to 6 percent, and the audit time per project fell from half a day to ten minutes.
  10. Retire: two older routines are removed from the startup files, once the new tool covers their functions.

It was not clever code. It was a clear specification, a read-only first version, a pilot, an owner and a retirement plan.


Common Mistakes

  • Automating before standardizing.
  • Ownerless code, loaded from forgotten folders.
  • No source control or no source at all.
  • Tools that change data by default, with no report and no undo.
  • Testing on live drawings.
  • Hard-coded paths and layer names that break on the next project.
  • Not restoring system variables.
  • Climbing to .NET when a script would do, or staying with LISP when the tool has outgrown it.
  • Ignoring version changes until the upgrade breaks everything.
  • Weak security: untrusted locations, unreviewed third-party code.
  • Not documenting.
  • Never retiring old tools.
  • Overloading one person as the only maintainer.

Best Practices

  • Standardize first, automate second.
  • Pick the lowest rung that works.
  • Make tools safe: read-only first, undo groups, logs, tests on copies.
  • Govern the code: owners, version control, change logs, staging, release notes.
  • Deploy centrally, from a trusted, read-only location.
  • Document and train.
  • Test each new software release before the office upgrades.
  • Review and retire regularly.
  • Combine tools: Python for audits, LISP for quick commands, .NET for products, FME and GDAL for conversion.
  • Measure the benefit, so the work is visible and funded.

Final Thoughts

The routine that deleted our layers was written by someone who was trying to help, in an office that had no way to know it was still running. I did not blame the author, and I did not blame the software. I blamed the absence of governance, which was my job. Within a month, we had an inventory of every tool loaded on every machine, an owner for each and a plan to retire the rest. The inventory itself took two days. It found eleven routines that nobody could explain.

If you are starting out, don’t begin with code. Begin with a list: what do people in your office do repeatedly, by hand, every week? Pick the one that is the most boring and the most error-prone, write it down as a specification, and automate it at the lowest rung that works, read-only first. Then give it an owner, a version and a place in the log. The code is the easy part. The discipline is what lets the office sleep.

Where to go next: run your tools across an archive with Batch Processing DWG Files: Core Console, Scripts and FME, and move into the civil side of the API in Dynamo and the Civil 3D API for Automation.

Rachid Khouri

Rachid Khouri

Rachid Khouri is a CAD, BIM and GIS professional, Autodesk Authorized Developer, trainer and technical author with more than 30 years of experience, working with AutoCAD since 1992. He founded GISauthority.com to share practical guidance on GIS and spatial technologies.