It is a common task to create and save a family document. Here we go.
public static RvtDocument CreateFamily(RvtApplication app, string fileNameToSave, string templateName)
{
if (File.Exists(fileNameToSave))
{
File.Delete(fileNameToSave);
}
string famTemplatePath = app.FamilyTemplatePath;
string templateFullName = Path.Combine(famTemplatePath, templateName + ".rft");
Document famDoc = app.NewFamilyDocument(templateFullName);
famDoc.SaveAs(fileNameToSave);
return famDoc;
}
public static RvtDocument GetOpenOrCreateFamilyTestDoc(UIApplication uiapp)
{
const string fileName = @"c:\temp\TestCreationInFamily.rfa";
RvtDocument famDoc = (from RvtDocument doc in uiapp.Application.Documents
where doc.PathName.Equals(fileName, StringComparison.CurrentCultureIgnoreCase)
select doc).FirstOrDefault();
if (famDoc == null)
{
if (File.Exists(fileName))
{
famDoc = uiapp.OpenAndActivateDocument(fileName).Document;
}
else
{
famDoc = CreationInFamily.CreateFamily(uiapp.Application, fileName, @"Generic Model");
}
}
return famDoc;
}
The CreateFamily method is pretty straightforward, but the GetOpenOrCreateFamilyTestDoc one is not. The latter does three things. First, find whether the specified family document has been loaded into Revit and if it does the document instance will be returned; second, the family has not the method will check whether it exists and if it does the family file will be opened and activated in the Revit session; last, if the first two cases all fail, a new family document will be created and saved to the location as specified.
Revit Addin Wizard (RevitAddinWizard) provides various wizards, coders and widgets to help program Revit addins. It can be downloaded from the Download link at the bottom of the blog index page.