Community
Hello Forum,
I have code that throws the following error:
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
At Autodesk.AutoCAD.ApplicationServices.Document.CloseInternal()
At Autodesk.AutoCAD.ApplicationServices.Document.CloseAndSave()
It only happens with some drawings.
Why would "Document.CloseAndSave()" throw this error? How can I prevent this/check if the document is ok to be closed and saved?
using (Document docTarget = CADS.Application.DocumentManager.Open(strTargetDwgPath, false)) { try { if (!docTarget.IsReadOnly) { using (DocumentLock dlTarget = docTarget.LockDocument()) { using (Transaction transTarget = docTarget.Database.TransactionManager.StartTransaction()) { btTarget = transTarget.GetObject(docTarget.Database.BlockTableId, OpenMode.ForRead) as BlockTable; foreach (string strDwgPath in strSourceDwgPathList) { ++intIndex; if (btTarget.Has(System.IO.Path.GetFileNameWithoutExtension(strDwgPath))) { using (Database dbInsert = new Database(false, true)) { dbInsert.ReadDwgFile(strDwgPath, System.IO.FileShare.Read, true, ""); oidInsert = docTarget.Database.Insert(System.IO.Path.GetFileNameWithoutExtension(strDwgPath), dbInsert, true); } btrInsert = transTarget.GetObject(oidInsert, OpenMode.ForWrite) as BlockTableRecord; if (btrInsert.IsDynamicBlock) btrInsert.UpdateAnonymousBlocks(); ++intFound; } else ++intNotFound; } btTarget = null; transTarget.Commit(); } } // Save changes. docTarget.CloseAndSave(strTargetDwgPath); // <<<< ERROR. enuResult = DialogResult.OK; } else { docTarget.CloseAndDiscard(); mstrMessage = "Failed: file is readonly or in use."; enuResult = DialogResult.Cancel; } } catch (System.Exception Ex) { MessageBox.Show(Ex.ToString(), "A"); mstrMessage = "Error redefining blocks in multiple drawings: " + Ex.Message + " (" + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + ")."; if (docTarget != null) { docTarget.CloseAndDiscard(); } enuResult = DialogResult.Cancel; } }