Give this a whirl:
using System;
using System.IO;
using System.Runtime.InteropServices;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using acadApp = Autodesk.AutoCAD.ApplicationServices.Application;
namespace XrefBind
{
public class Class1
{
[DllImport("acdb17.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode,
EntryPoint = "?acdbBindXrefs@@YA?AW4ErrorStatus@Acad@@PAVAcDbDatabase@@ABV?$AcArray@VAcDbObjectId@@V?$AcArrayMemCopyReallocator@VAcDbObjectId@@@@@@_N22@Z")]
extern public static ErrorStatus acdbBindXrefs(IntPtr pHostDb, IntPtr xrefObjectIds, bool bInsertBind, bool bAllowUnresolved, bool bQuiet);
// Define Command "BAX"
[CommandMethod("tcgsBAX")]
static public void BindAllXrefsCommand()
{
// Get the usual
Document doc = acadApp.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
// Has the drawing been saved?
if ((short)acadApp.GetSystemVariable("DBMOD") != 0)
{
ed.WriteMessage("{0}Drawing must be saved before continuing - please save the drawing and try again.",
Environment.NewLine);
return;
}
// Dbase for our bind
Database dbBind = null;
ObjectIdCollection xrefIds = null;
try
{
// Create the bind host dbase and read our dwg into it
dbBind = new Database(false, true);
dbBind.ReadDwgFile(db.Filename, System.IO.FileShare.ReadWrite, false, null);
// Resolve any xrefs
dbBind.ResolveXrefs(true, false);
// Get the xref graph for the current dbase...
XrefGraph xrefGraph = dbBind.GetHostDwgXrefGraph(true);
if (xrefGraph == null || xrefGraph.IsEmpty || xrefGraph.NumNodes == 1)
{
ed.WriteMessage("{0}No xrefs found.", Environment.NewLine);
return; // No xrefs...
}
// Not allowing unresolved xrefs, however we could by changing
// 4th argument to true of acdbBindXrefs
if (xrefGraph.MarkUnresolvedTrees())
{
ed.WriteMessage("\nWarning: There are unresolved xrefs - bind aborted!");
return;
}
for (int i = 0; i < xrefGraph.NumNodes; i++)
{
XrefGraphNode xrefGraphNode = xrefGraph.GetXrefNode(i);
if (xrefGraphNode == null)
{
ed.WriteMessage("\nError: Failed to get a node on the graph - aborting!");
return;
}
// Is it the root node, which is the current drawing?
// If it IS, then the number of incoming nodes will be 0...
if (xrefGraphNode == xrefGraph.HostDrawing)
continue;
// Continue if it's truly nested as we can only bind "true" top level parents...
if (xrefGraphNode.IsNested)
continue;
if (xrefGraphNode.NumIn == 1)
{
if (xrefIds == null)
xrefIds = new ObjectIdCollection();
xrefIds.Add(xrefGraphNode.BlockTableRecordId);
}
}//for
ErrorStatus es = ErrorStatus.OK;
// Try to bind
es = acdbBindXrefs(dbBind.UnmanagedObject, xrefIds.UnmanagedObject, true, false, false);
string fullFileName = dbBind.Filename;
string filePath = Path.GetDirectoryName(fullFileName);
string fileName = Path.GetFileNameWithoutExtension(fullFileName);
string timeStamp = DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss");
string newFileName = Path.Combine(filePath, fileName + "_" + timeStamp + ".dwg");
// try to save
dbBind.RetainOriginalThumbnailBitmap = true;
dbBind.SaveAs(newFileName, DwgVersion.Current);
}
catch (System.Exception ex)
{
ed.WriteMessage("{0}Error: {1}", Environment.NewLine, ex.Message);
}
finally
{
if (dbBind != null)
dbBind.Dispose();
}
}
}
}
Usual disclaimer applies - "all care taken, no responsibility implied". Test on copies of live data etc.