using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using OpenFileDialog = Autodesk.AutoCAD.Windows.OpenFileDialog;
namespace Xdata
{
public static class Class1
{
public static List<string> SelectDrawings()
{
List<string> fileNames = new List<string>();
try
{
OpenFileDialog ofd = new OpenFileDialog("Выбрать чертеж", "", "dwg", "did", OpenFileDialog.OpenFileDialogFlags.AllowMultiple);
DialogResult yy = ofd.ShowDialog();
if (yy == DialogResult.OK)
{
foreach (string file in ofd.GetFilenames())
{
fileNames.Add(file);
}
}
}
catch (System.Exception ex)
{
Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(ex.ToString());
}
return fileNames;
}
public static void GetObjects(Database db)
{
List<Entity> entities = new List<Entity>();
try
{
Transaction tr = db.TransactionManager.StartTransaction();
using (tr)
{
BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead, false, true);
BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
foreach (ObjectId item in btr)
{
Entity ent = (Entity)tr.GetObject(item, OpenMode.ForWrite, false, true);
entities.Add(ent);
}
foreach (var ent in entities)
{
ClearXData(ent);
}
tr.Commit();
}
}
catch (System.Exception ex)
{
Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(ex.ToString());
}
}
public static void ClearXData(Entity item)
{
ResultBuffer rb = item.XData;
if (rb != null)
{
item.XData = new ResultBuffer();
}
}
[CommandMethod("CXD")]
public static void SynchronizeDrawings()
{
List<string> fileNames = SelectDrawings();
if (fileNames.Count == 0)
{
return;
}
Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Database destDb = acDoc.Database;
ObjectId idMSpace = ObjectId.Null;
using (Transaction acTrans = destDb.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = acTrans.GetObject(destDb.BlockTableId, OpenMode.ForRead, false, true) as BlockTable;
idMSpace = acBlkTbl[BlockTableRecord.ModelSpace];
var startTime = System.Diagnostics.Stopwatch.StartNew();
foreach (string fileName in fileNames)
{
using (Database sourceDb = new Database(false, true))
{
sourceDb.ReadDwgFile(fileName, FileOpenMode.OpenForReadAndAllShare, false, null);
GetObjects(sourceDb);
sourceDb.SaveAs(fileName, DwgVersion.Current);
}
}
acTrans.Commit();
}
}
}
}