using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using System.IO;
using System;
namespace Purger
{
public class Commands
{
[CommandMethod("PC")]
public void PurgeCurrentDocument()
{
Document doc =
Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
int count =
PurgeDatabase(db);
ed.WriteMessage(
"\nPurged {0} object{1} from " +
"the current database.",
count,
count == 1 ? "" : "s"
);
}
private static int PurgeDatabase(Database db)
{
int idCount = 0;
Transaction tr =
db.TransactionManager.StartTransaction();
using (tr)
{
// Create the list of objects to "purge"
ObjectIdCollection idsToPurge =
new ObjectIdCollection();
// Add all the Registered Application names
LayerTable LT =
(LayerTable)tr.GetObject(
db.LayerTableId,
OpenMode.ForRead
);
foreach (ObjectId LtId in LT)
{
if (LtId.IsValid)
{
idsToPurge.Add(LtId);
}
}
// Call the Purge function to filter the list
db.Purge(idsToPurge);
Document doc =
Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
ed.WriteMessage(
"\nLayers being purged: "
);
// Erase each of the objects we've been
// allowed to
foreach (ObjectId id in idsToPurge)
{
DBObject obj =
tr.GetObject(id, OpenMode.ForWrite);
// Let's just add to me "debug" code
// to list the registered applications
// we're erasing
LayerTableRecord LTR =
obj as LayerTableRecord;
if (LTR != null)
{
ed.WriteMessage(
"\"{0}\" ",
LTR.Name
);
}
obj.Erase();
}
// Return the number of objects erased
// (i.e. purged)
idCount = idsToPurge.Count;
tr.Commit();
}
return idCount;
}
}
}