It is pretty easy to reproduce:
[Transaction(TransactionMode.Manual)]
[Regeneration(RegenerationOption.Manual)]
[Journaling(JournalingMode.NoCommandData)]
public class DrieBToolTest : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Document doc = uidoc.Document;
// select some elements in the first document
FilteredElementCollector notElemTypeCtor = (new FilteredElementCollector(doc, uidoc.ActiveGraphicalView.Id)).WhereElementIsNotElementType();
List<ElementId> theelems = notElemTypeCtor.ToList().Select(theelem => theelem.Id).ToList();
// open the second file and do some actions
string fam = @"d:\test\fam\31_3B_vo bu deur met weerszijde 2 zijlichten.rfa";
UIDocument famDoc = commandData.Application.OpenAndActivateDocument(fam);
Transaction transac = new Transaction(famDoc.Document);
transac.Start("change scale");
famDoc.ActiveView.get_Parameter(BuiltInParameter.VIEW_SCALE_PULLDOWN_METRIC).Set(20);
transac.Commit();
SaveAsOptions opt = new SaveAsOptions { OverwriteExistingFile = true };
famDoc.Document.SaveAs(fam, opt);
// On a new file the doc,PathName is empty
if (!string.IsNullOrEmpty(doc.PathName))
{
commandData.Application.OpenAndActivateDocument(doc.PathName);
famDoc.Document.Close(false); // no problem here
}
else
{
// this is the way to go when to avoid using OpenAndActivateDocument
uidoc.ShowElements(theelems);
uidoc.RefreshActiveView();
famDoc.Document.Close(false); //here revit throws the exception and doesn't close the file
}
return Result.Succeeded;
}