An AutoCAD Script

By Brady • Portfolio • 2 Jun 2014

A month or so ago, a friend asked me for a script to turn off the same layer name in a fairly large group of files.  This is how I managed to make that work.  Be sure to install and reference the Object ARX and AutoCAD DotNet Wizards, available under tools, HERE.

Build this into a .dll.  Open AutoCAD, and using the command line run the netload command.  Direct the file prompt to the location of your .dll.  AutoCAD will ask you to verify that you want to load that file.  Say yes.  Then, using the command line again run the TurnOffLayers command.  The application will ask you through the command line which layer you want to turn off.  The script does the rest.

namespace turnOffLayer
{
public class LinkGenerator
{
[CommandMethod("TurnOffLayers", CommandFlags.Session)]
public void turnOffLayers()
{
//get currently active doc
Document doc = Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
//get directory of DWG files
string dwgPath = ed.GetString(“Enter DWG Folder path: “).StringResult;
//get layer name that needs to be turned off
string layerName = ed.GetString(“Enter layer name: “).StringResult;

//process each file
foreach (var dwfFileName in Directory.GetFiles(dwgPath, “*.dwg”, System.IO.SearchOption.AllDirectories))
{
ed.WriteMessage(“\nProcessing: {0}”, dwfFileName);
layerOff(dwfFileName, layerName);
}
ed.WriteMessage(“\nProcessing complete”);
}

//switch to doc, turn off layer, save doc.
public static void layerOff(String dwfFileName, string layer)
{
DocumentCollection acDocMgr = Application.DocumentManager;
Document Drawing1 = acDocMgr.MdiActiveDocument;

if (File.Exists(dwfFileName))
{
Application.DocumentManager.MdiActiveDocument = acDocMgr.Open(dwfFileName);
}
AcadApplication app = Application.AcadApplication as AcadApplication;
// Get the current document and database, and start a transaction
Document acDoc = Application.DocumentManager.MdiActiveDocument;
acDoc.LockDocument();
Database acCurDb = acDoc.Database;

using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Layer table for read
LayerTable acLyrTbl;
acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable;
foreach (ObjectId oID in acLyrTbl)
{
LayerTableRecord ltr = (LayerTableRecord)acTrans.GetObject(oID, OpenMode.ForWrite);
if (ltr.Name.Contains(layer))
{
ltr.IsOff = true;
}
}

acTrans.Commit();
Application.DocumentManager.MdiActiveDocument = Drawing1;
acDoc.CloseAndDiscard();
}
// Update the display
acDoc.Editor.Regen();
}
}
}