参照されていない名前の付いたオブジェクトは、いつでもデータベースから削除できます。他のオブジェクトから参照されている名前の付いたオブジェクトは削除できません。たとえば、フォント ファイルが文字スタイルによって参照されている場合や、画層がその画層上のオブジェクトによって参照されている場合があります。削除することによって、ディスクに保存したときの図面ファイルのサイズが小さくなります。
参照されていないオブジェクトは、Purge メソッドを使用して図面データベースから削除されます。Purge メソッドは、削除するオブジェクトの一覧を、ObjectIdCollection または ObjectIdGraph オブジェクトの形式で必要とします。Purge メソッドに渡される ObjectIdCollection または ObjectIdGraph オブジェクトは、データベースから消去できるオブジェクトによって更新されます。Purge を呼び出した後、返された個々のオブジェクトを消去する必要があります。
次の例では、データベースから参照されていない画層を削除する方法を示しています。
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
[CommandMethod("PurgeUnreferencedLayers")]
public static void PurgeUnreferencedLayers()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;
// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Layer table for read
LayerTable acLyrTbl;
acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
OpenMode.ForRead) as LayerTable;
// Create an ObjectIdCollection to hold the object ids for each table record
ObjectIdCollection acObjIdColl = new ObjectIdCollection();
// Step through each layer and add iterator to the ObjectIdCollection
foreach (ObjectId acObjId in acLyrTbl)
{
acObjIdColl.Add(acObjId);
}
// Remove the layers that are in use and return the ones that can be erased
acCurDb.Purge(acObjIdColl);
// Step through the returned ObjectIdCollection
// and erase each unreferenced layer
foreach (ObjectId acObjId in acObjIdColl)
{
SymbolTableRecord acSymTblRec;
acSymTblRec = acTrans.GetObject(acObjId,
OpenMode.ForWrite) as SymbolTableRecord;
try
{
// Erase the unreferenced layer
acSymTblRec.Erase(true);
}
catch (Autodesk.AutoCAD.Runtime.Exception Ex)
{
// Layer could not be deleted
Application.ShowAlertDialog("Error:\n" + Ex.Message);
}
}
// Commit the changes and dispose of the transaction
acTrans.Commit();
}
}