private void LayTrans(Dictionary<string, string> layerNames, string fileName) { Document doc = AcAp.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; using (Transaction tr = db.TransactionManager.StartTransaction()) { LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead); List<string> toRemove = new List<string>(); foreach (KeyValuePair<string, string> pair in layerNames) { if (!lt.Has(pair.Key)) { ed.WriteMessage("\nTarget drawing does not contain '{0}'", pair.Key); toRemove.Add(pair.Key); } } foreach (string layer in toRemove) { layerNames.Remove(layer); } List<LayerTableRecord> oldLayers = new List<LayerTableRecord>(); using (Database sourceDb = new Database()) { sourceDb.ReadDwgFile(fileName, System.IO.FileShare.Read, false, ""); using (Transaction trx = sourceDb.TransactionManager.StartTransaction()) { LayerTable sourceTable = (LayerTable)trx.GetObject(sourceDb.LayerTableId, OpenMode.ForRead); ObjectIdCollection idCol = new ObjectIdCollection(); foreach (KeyValuePair<string, string> pair in layerNames) { if (sourceTable.Has(pair.Value)) { idCol.Add(sourceTable[pair.Value]); LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(lt[pair.Key], OpenMode.ForWrite); oldLayers.Add(ltr); } else { ed.WriteMessage("\nSource drawing does not contain '{0}'", pair.Value); } } foreach (LayerTableRecord ltr in oldLayers) { ltr.Name = "Old_" + ltr.Name; } IdMapping idMap = new IdMapping(); sourceDb.WblockCloneObjects( idCol, db.LayerTableId, idMap, DuplicateRecordCloning.Ignore, false); trx.Commit(); } } BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); foreach (ObjectId btrId in bt) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(btrId, OpenMode.ForRead); foreach (ObjectId id in btr) { Entity ent = (Entity)tr.GetObject(id, OpenMode.ForRead); if (ent.Layer.StartsWith("Old_")) { string name = ent.Layer.Substring(4); ent.UpgradeOpen(); ent.Layer = layerNames[name]; } } } foreach (LayerTableRecord ltr in oldLayers) { ltr.Erase(); } tr.Commit(); } }