I am trying to delete all layouts from the drawing without opening it. This code works well, but AFTER all code is finished (successfully) the AutoCAD throws unhandled exception (without any usable output) and crashes. I found out, that this error is caused by setting and resetting WorkingDatabase, but there's no other way to delete layouts without opening DWG in DocumentManager (I tried that, but when you have a lot of drawings, it takes ages to finish).
Is there a way to catch this unhandled exception or any other working solution? Any help appreciated. Thanks.
Imports Autodesk.AutoCAD.DatabaseServices Imports System.Windows.Forms Imports System.IO Public Class Clear Public Function ClearDrawing(ByVal dwg As String, ByVal tempDwg As String) As Boolean Using docDB As New Database(False, True) Try docDB.ReadDwgFile(tempDwg, FileOpenMode.OpenForReadAndWriteNoShare, True, "") docDB.CloseInput(True) Dim curDB As Database = HostApplicationServices.WorkingDatabase 'save working DB HostApplicationServices.WorkingDatabase = docDB 'set new DB as working DB Using tr As Transaction = docDB.TransactionManager.StartTransaction Try LayoutManager.Current.CurrentLayout = "Model" LayoutManager.Current.CreateLayout("_#empty") 'need to create empty layout, because otherwise it will says it's demaged drawing when opening it Dim layoutDict As DBDictionary = CType(tr.GetObject(docDB.LayoutDictionaryId, OpenMode.ForWrite), DBDictionary) For Each de As DBDictionaryEntry In layoutDict Dim layoutName As String = de.Key If (layoutName.ToLower <> "model" And layoutName <> "_#empty") Then LayoutManager.Current.DeleteLayout(layoutName) End If Next LayoutManager.Current.RenameLayout("_#empty", "Layout1") 'rename to standard name LayoutManager.Current.CurrentLayout = "Model" tr.Commit() Catch ex As Exception tr.Abort() MessageBox.Show("Error during deleting layouts:" & ex.Message & ex.StackTrace, "Delete layouts error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Using HostApplicationServices.WorkingDatabase = curDB 'reset working databse 'Create directiories if they not exist If Not Directory.Exists(Path.GetDirectoryName(dwg)) Then Directory.CreateDirectory(Path.GetDirectoryName(dwg)) End If Try Dim newDb As Database = docDB.Wblock newDb.SaveAs(dwg, DwgVersion.Current, DwgVersion.Current, docDB.SecurityParameters) Catch ex As Exception MessageBox.Show("Unable to save Wblock db: " & ex.Message & ex.StackTrace) End Try Return True Catch ex As Exception MessageBox.Show("Unable to process drawing: " & ex.Message & ex.StackTrace) Return False End Try End Using End Function End Class
Set the working database is not very safe... but in this case is necessary.
Try store the old working database, and after you're done, set it back to its original value.
Hi...i am also facing the similar kind of fatal error when i try to rename the layouts. @Anonymous have you found any solution for this error?