When doing LayoutManager operations on external DWGs through the ReadDwgFile() method, I got some pretty strange behavior. The solution that worked for me was to set the active layout to be modelspace before and after doing operations. Hopefully this will save someone some time. From what I've gathered this must be a bug in the LayoutManager itself, probably related to cached viewports or a regen, as the code worked perfectly as long as I used it on DWGs I had opened.
Example:
//My code is looping through all the layouts in a DWG looking for one specific layout that I know the name of.
//All the other layouts are to be deleted.
DBDictionary layouts;
Database externalDatabase = new Database(false, true);
externalDatabase.ReadDwgFile(@"C:\Users\MyUser\Drawing.dwg", FileOpenMode.OpenForReadAndAllShare, true, "");
HostApplicationServices.WorkingDatabase = externalDatabase;
ObjectId modelSpaceId = LayoutManager.Current.GetLayoutId("Model");
using (var transaction = externalDatabase.TransactionManager.StartTransaction())
{
//In the method I use I have to set OpenMode.ForWrite
//but in most cases I guess OpenMode.ForRead would be enough
layouts = (DBDictionary)transaction.GetObject(externalDatabase.LayoutDictionaryId, OpenMode.ForWrite);
transaction.Commit();
transaction.Dispose();
}
foreach (DBDictionaryEntry layout in layouts)
{
if (String.Equals(layout.Key, "Model"))
{
continue;
}
else if (String.Equals(layout.Key, "Name Of Layout To Keep"))
{
continue;
}
else
{
LayoutManager.Current.SetCurrentLayoutId(modelSpaceId);
LayoutManager.Current.DeleteLayout(layout.Key);
LayoutManager.Current.SetCurrentLayoutId(modelSpaceId);
}
}
//Don't forget to switch HostApplicationServices.WorkingDatabase back to the original database
I found this thread on Google when I looked for people having the same issue as me, so in case anyone else finds this thread I thought it was cleaner to post the solution here rather than creating my own thread.