Detach FileNotFound Xrefs from DWG

Looking for some help as I looked hard and only found C# solution online for the problem I am facing.
I have dwg file with some xrefs that don’t exists in the link specified. I want to loop over each and remove only those from the file. Below is what I have:

with adoc.LockDocument():
	with adoc.Database as db:
		with db.TransactionManager.StartTransaction() as t:
			bt = t.GetObject(db.BlockTableId, OpenMode.ForRead)
			btr = t.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead)

			for oid in btr:
				bl = t.GetObject(oid, OpenMode.ForRead)
				if isinstance(bl, BlockReference):
					if bl.BlockTableRecord.IsFromExternalReference:
						xrefId = bl.BlockTableRecord;
						xrefs.append(bl.Name)
			
OUT = xrefs

I got the above snippet from one of the questions here. I think this has to do with XrefGraph but I don’t know how to call that class in python or even if it exists. Here is one solution that is implemented in C#: https://forums.autodesk.com/t5/net/net-c-unable-to-detaching-filenotfound-xref-without-opening-the/m-p/3573496#M30498

Figured it out by myself. If anyone is looking for this solution:

with adoc.LockDocument():
	with adoc.Database as db:
		with db.TransactionManager.StartTransaction() as t:
			xg = db.GetHostDwgXrefGraph('true')		 
			xrefcount = xg.NumNodes
			for x in range(xrefcount):
				xrNode = xg.GetXrefNode(x)
				nodeName = xrNode.Name
				if xrNode.XrefStatus == XrefStatus.FileNotFound:
					detachid = xrNode.BlockTableRecordId;
					db.DetachXref(detachid);
			t.Commit();
			
OUT = xrefcount

3 Likes