using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.EditorInput; using Autodesk.AutoCAD.Runtime; namespace ExtractObjects { public class Commands { [CommandMethod("RDKPURGEFILES")] static public void cmdRdkPurgeFiles() { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter filepath: "); pStrOpts.AllowSpaces = true; PromptResult pStrRes = ed.GetString(pStrOpts); if (pStrRes.Status == PromptStatus.OK) // check valid string input { ed.WriteMessage("Filepath is: {0}", pStrRes.StringResult); string filepath = pStrRes.StringResult; DirectoryInfo d = new DirectoryInfo(filepath); foreach (var dwgfile in d.GetFiles("*.dwg", SearchOption.TopDirectoryOnly)) { ed.WriteMessage("\nStart file: " + dwgfile.Name); // Create a database and try to load the file Database db = new Database(false, true); using (db) { try { db.ReadDwgFile(dwgfile.FullName,FileOpenMode.OpenForReadAndAllShare,true,null); // open the dwg file ObjectIdCollection ids = new ObjectIdCollection(); Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { DBDictionary matDict = (DBDictionary)tr.GetObject(db.MaterialDictionaryId, OpenMode.ForRead, false); foreach (DBDictionaryEntry entry in matDict) { string key = entry.Key; if ((key != "ByBlock") && (key != "ByLayer") && (key != "Global")) ids.Add(entry.Value); } db.Purge(ids); foreach (ObjectId id in ids) { DBObject obj = (DBObject)tr.GetObject(id, OpenMode.ForWrite); obj.Erase(); } tr.Commit(); ed.WriteMessage("\nMaterials purged in: " + dwgfile.FullName); db.SaveAs(dwgfile.FullName, true, DwgVersion.AC1024, null); // save as dwg2010 and create a BAK file } } //try catch (System.Exception e) { ed.WriteMessage("\nUnable to access file:" + dwgfile.FullName); ed.WriteMessage("\nException is: " + e.Message); db.Dispose(); // close transaction } //db.Dispose(); // close transaction } // end db } // end foreach } // end if else { ed.WriteMessage("Invalid string input: " + pStrRes.Status.ToString()); } } //end method } }