Want to have C# program to modify DWG and save into DWG format

Want to have C# program to modify DWG and save into DWG format

vsraman85
Explorer Explorer
3,341 Views
20 Replies
Message 1 of 21

Want to have C# program to modify DWG and save into DWG format

vsraman85
Explorer
Explorer

Hi,

I have installed the trail version of AutoCAD and ObjectARX SDK. My objective is to write a C# program to read DWG file, do some modifications, and then save it as another DWG file. I referenced autodesk dll's as per documentation, but program throws a Common Language Runtime error. Can anyone please throw some light on this?I am using Visual Studio 2022. Please suggest what kid of template i need to use for this as well?

0 Likes
3,342 Views
20 Replies
Replies (20)
Message 2 of 21

_gile
Consultant
Consultant

Hi,

It is very difficult (if not impossible) to diagnoze without seeing the code which throws the error.



Gilles Chanteau
Programmation AutoCAD LISP/.NET
GileCAD
GitHub

0 Likes
Message 3 of 21

vsraman85
Explorer
Explorer

Hi,

I am using Visual studio 2022. tried the same code as Class library, Windows form application (.net framework 4.7).

Here you go with my code in C#.

1. Created winodws form application with C# template in Visual studio.

2. Target framework as .net framework 4.7

3. Added below autodesk reference.

vsraman85_1-1702481379180.png

4. Build is succeeded without any error.

5. The moment when i run, it has started throwing below error.

 

vsraman85_0-1702481239821.png

Note : The same error was throwing in document line, hence i commented those lines but it has started throwing in transaction lines.

 

Class Library

1. Same code is tried in Class library.

2. Build is success.

3. Opened the AutoCAD application, in command prompt, entered netload.

4. Selected my class library dll. no error, success till to this point.

5. In my program, i have a command method "ModifyDWG", hence I typed it in command prompt, AutoCAD is not regnoizing that command and nothing is happening.

vsraman85_2-1702481699519.png

0 Likes
Message 4 of 21

vsraman85
Explorer
Explorer

Hi,

I am using Visual studio 2022. tried the same code as Class library, Windows form application (.net framework 4.7).

Here you go with my code in C#.

1. Created winodws form application with C# template in Visual studio.

2. Target framework as .net framework 4.7

3. Added below autodesk reference.

vsraman85_1-1702481379180.png

4. Build is succeeded without any error.

5. The moment when i run, it has started throwing below error.

 

vsraman85_0-1702481239821.png

Note : The same error was throwing in document line, hence i commented those lines but it has started throwing in transaction lines.

 

Class Library

1. Same code is tried in Class library.

2. Build is success.

3. Opened the AutoCAD application, in command prompt, entered netload.

4. Selected my class library dll. no error, success till to this point.

5. In my program, i have a command method "ModifyDWG", hence I typed it in command prompt, AutoCAD is not regnoizing that command and nothing is happening.

vsraman85_2-1702481699519.png

0 Likes
Message 5 of 21

_gile
Consultant
Consultant

If you want to be able to use the AutoCAD .NET API, you have to build a DLL (class library) and netload it from a running session of AutoCAD  (with a Windows application (exe) you have to use the COM API).

You can start from this topic.



Gilles Chanteau
Programmation AutoCAD LISP/.NET
GileCAD
GitHub

0 Likes
Message 6 of 21

vsraman85
Explorer
Explorer

Thanks. But class library netload is also not working with same code. Can I get any sample code for reading, modifying and saving as new DWG in C#?

0 Likes
Message 7 of 21

_gile
Consultant
Consultant

Here's a generic example which takes a delegate (Action<Database>) as argument.

public static void ProcessDwg(string fileName, Action<Database> action)
{
    try
    {
        using (var db = new Database(false, true))
        {
            db.ReadDwgFile(fileName, FileOpenMode.OpenForReadAndAllShare, false, null);
            action(db);
            db.SaveAs(fileName, DwgVersion.Current);
        }
    }
    catch (System.Exception ex)
    {
        var ed = Application.DocumentManager.MdiActiveDocument.Editor;
        ed.WriteMessage($"\nError with '{fileName}': {ex.Message}");
    }
}

 

From your example:

private static void AddMText(Database db)
{
    using (var tr = db.TransactionManager.StartTransaction())
    {
        var modelSpace = (BlockTableRecord)tr.GetObject(
            SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite);
        var mtext = new MText()
        {
            Location = new Point3d(2, 2, 0),
            Contents = "added text in a closed .dwg file!"
        };
        modelSpace.AppendEntity(mtext);
        tr.AddNewlyCreatedDBObject(mtext, true);
        tr.Commit();
    }
}

 

Doing so, you can test the AddMtext method in the current database and/or pass it to ProcessDwg.

ProcesDwg(filename, AddMtext);


Gilles Chanteau
Programmation AutoCAD LISP/.NET
GileCAD
GitHub

0 Likes
Message 8 of 21

ActivistInvestor
Mentor
Mentor

A minor embellishment to @_gile 's example, which may be necessary in certain circumstances:

 

 

public static class Unnamed
{
   public static void ProcessDwg(string fileName, Action<Database> action)
   {
      try
      {
         using(var db = new Database(false, true))
         {
            db.ReadDwgFile(fileName, FileOpenMode.OpenForReadAndAllShare, false, null);
            using(new WorkingDatabase(db))
            {
               action(db);
               db.SaveAs(fileName, DwgVersion.Current);
            }
         }
      }
      catch(System.Exception ex)
      {
         var ed = Application.DocumentManager.MdiActiveDocument.Editor;
         ed.WriteMessage($"\nError with '{fileName}': {ex.Message}");
      }
   }
}

public class WorkingDatabase : IDisposable
{
   Database previous;

   public WorkingDatabase(Database newWorkingDb)
   {
      if(newWorkingDb == null)
         throw new ArgumentNullException(nameof(newWorkingDb));
      Database current = HostApplicationServices.WorkingDatabase;
      if(newWorkingDb != current)
      {
         previous = current;
         HostApplicationServices.WorkingDatabase = newWorkingDb;
      }
   }

   public void Dispose()
   {
      if(previous != null)
      {
         HostApplicationServices.WorkingDatabase = previous;
         previous = null;
      }
   }
}

 

Message 9 of 21

vsraman85
Explorer
Explorer

I have tried the above said coding, ended up with the same error again.

vsraman85_0-1702511472727.png

 

0 Likes
Message 10 of 21

vsraman85
Explorer
Explorer

I have tried the same, ended with same existing error.

vsraman85_0-1702511522562.png

 

0 Likes
Message 11 of 21

ActivistInvestor
Mentor
Mentor

You show a screenshot but it does not show the exception message or stacktrace.

 

 

0 Likes
Message 12 of 21

norman.yuan
Mentor
Mentor

If "...with the same existing error" means the "common Language runtime error" described in your original post, it means:
You write/run the code in wrong project type. Is it .NET Framework 4.x class library? if yes, do you run AutoCAD and "netload" the DLL into AutoCAD, then enter the command declared by [CommandMethod("XXX")] attribute? Or, have you set the "Copy Local" to False for the 3 AutoCAD .NET API DLLs? Or, your project is .NET Core (.NET 5, 6, 7, or 8 class library. Of course, if you still try to run do an EXE app, it will not work, as @_gile has pointed out earlier.

You probably need to show/describe how you start the class library project.

Norman Yuan

Drive CAD With Code

EESignature

0 Likes
Message 13 of 21

vsraman85
Explorer
Explorer

Thanks for the response. It's my bad that i did it in Windows form application. Now I am able to do the same thing in Class library (.NET Framework 4.7), and did the netload in AutoCAD. And then able to do the command in Autocad. I am not receiving any error, as per program it is adding some MText into DWG file and saves it. However, when i open that saved file in Autocad, not able to see that added text. How to check it? It would be good if below questions are clarified as well. 1. How to do the same thing through Windows form Application (.NET Framework). 2. Is it possible to modify and save DWG file withoutAutoCAD installation? I see something like RealDWG, which is subset of Autodesk ObjetARX? Need more clarity on this. Can I use .net core windows application as well to do the same? Please throw some light here to proceed further 

0 Likes
Message 14 of 21

vsraman85
Explorer
Explorer

I am able to doexecute the code in class library. But how should i do the same with windows form application? Can i use .net core or .net framework only allowed?  Where can i get sample code and steps to do this? If i am using .net windows application, should autocad to be installed in that machine? what is RealDWG? how can i use it? 

0 Likes
Message 15 of 21

norman.yuan
Mentor
Mentor

@_gile has already answered you (message 4 of this thread): AutoCAD .NET API assemblies CANNOT be used outside AutoCAD process (e.g. not in an EXE app). You cannot manipulate DWG File without using AutoCAD (except for using RealDwg SDK. However, judging by your questions, you seems do not know much in depth about AutoCAD/AutoCAD drawing, so, I'd say do not bother RealDwg).

 

You can use an EXE (.NET Framework, or .NET Core, not much difference) to automate AutoCAD application (desktop) via AutoCAD COM API, but it is a bad solution in most cases, because the user has to face/deal with 2 desktop apps, while the task can most likely be done by just run AutoCAD with properly designed .NET API plugins.

 

If your objectives is to prepare a drawing file before handling it for user to work with in AutoCAD and want to do the preparation at backend, you still need AutoCAD of some forms: either AutoCAD console, or AutoCAD online (Autodesk's Platform Cloud Services, which is basically AutoCAD console in the cloud). However, you still need to learn how to program AutoCAD .NET API plugin, before you can use AutoCAD console/Platform Services meaningfully. Once you can do .NET API plugin well, thus know how to manipulate drawing database/file well, you may one day look into the possibility of using RealDwg SDK (quite expensive) for your solution, because the code to deal with drawing database/file are mostly the same. Again, in the "everything is online" era, using cloud services would much simple/easier, and cheaper solution than licensing RealDwg to try build your own "mini AutoCAD" to deal with DWG file.

 

Norman Yuan

Drive CAD With Code

EESignature

0 Likes
Message 16 of 21

vsraman85
Explorer
Explorer

Hi,

Thanks for the clarification. Where can I download and how can i use Autodesk COM API for windows application EXE?

And also I don't see any separate downloadable of RealDWG. Is it part of ObjectARX? How to use it? There is no clear documentations avaialble.

0 Likes
Message 17 of 21

norman.yuan
Mentor
Mentor

There is nothing to download for using AutoCAD COM API, as long as AutoCAD is installed. If you ever did MS Office App automation (Word, Excel...), automating AutoCAD would be quite similar, but you DO NEED TO know AutoCAD well enough. You can install AutoCAD VBA module and use the Object Browser in AutoCAD VBA IDE to browse/learn AutoCAD COM API object model.

 

You need to pay to license RealDwg SDK (quite expensive). Search Autodesk's website for information of how to buy it. 

 

Not knowing what your objectives are/what you want to do, and feel that you do not know AutoCAD programming well enough, I can only say, trying to build EXE (desktop?) to automate another heavy desktop app (AutoCAD) would be one of the worst solutions among all possible ones, if not the worst one, in most cases. I'd also think it is waste time to look into RealDwg before you have deep understanding on AutoCAD programming, IMO.

 

 

Norman Yuan

Drive CAD With Code

EESignature

0 Likes
Message 18 of 21

vsraman85
Explorer
Explorer

Thanks for your response. Yes. I am completely new to this AutoCAD programming, exploring all possible options.

Below is my objective of my POC.

1. I would like to open a DWG file without the help of AutoCAD and wanted to do  it programmatically.

2. Do some modifications to the opened DWG file. ( Connecting lines, circles, etc)

3. Save the corrections and create them as a new DWG file.

 

Thanks

Venkat

 

 

0 Likes
Message 19 of 21

norman.yuan
Mentor
Mentor

You did not provide the business case/context of why you want to  do it "without the help of AutoCAD". So, the simple answer is:

 

No, without AutoCAD, you cannot manipulate DWG file, unless you use RealDwg SDK (again, I'd say forget using RealDwg until you are actually programming AutoCAD fluently with either AutoCAD .NET API or ObjectARC C++).

 

If you use Autodesk cloud services or host Acad console at your backend services, you could have a solution looking like "without the help of AutoCAD" to the users, but you actually use a remote AutoCAD without UI. Again, you need to be good at AutoCAD programming for choosing this route.

 

That is, if you want to manipulate DWG file, you ALWAYS start from USING AutoCAD and programming WITH AutoCAD.

 

Norman Yuan

Drive CAD With Code

EESignature

0 Likes
Message 20 of 21

vsraman85
Explorer
Explorer

Based on some business requirements, we wanted to draw lines, connect objects, add text through programmatically through back services, and save it as DWG. 

0 Likes