当进行一些插件功能的开发时,譬如按规则自动生成模型元素;生成时需要指定某个族文件,并对其进行调用;而用户的建模文件样板中可能并不存在该族文件,故需要在用户打开功能前,静默加载一个需要用到的族文件进入当前建模的文件。下面代码为当打开一个WPF窗体应用时载入族文件的示例:
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System;
using System.IO;
using System.Linq;
using Path = System.IO.Path;
namespace CreateElementSimple
{
[Transaction(TransactionMode.Manual)]
class RingBeamMainProgram : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
UIDocument uidoc = commandData.Application.ActiveUIDocument;
Document doc = uidoc.Document;
//获取嵌入的资源,族文件需要预先嵌入当前解决方案文件内,并将生成操作改为嵌入的资源
string resourceName = "CreateElementSimple.rfaFileName.rfa";
//提取嵌入的族文件并保存到%temp%临时缓存路径
string tempFilePath = ExtractEmbeddedResource(resourceName);
string rfaName = "rfaFileName";
//将族文件载入Revit项目,并按需重新命名
Family family = new FilteredElementCollector(doc).OfClass(typeof(Family)).FirstOrDefault(x => x.Name == rfaName) as Family;
if (family == null)
{
try
{
Transaction transaction = new Transaction(doc, "载入族");
transaction.Start();
doc.LoadFamily(tempFilePath, out family);
if (family != null)
{
family.Name = rfaName;
}
transaction.Commit();
}
catch (Exception /*ex*/)
{
//载入情况可输出为日志
}
}
//清理%temp%路径临时文件
File.Delete(tempFilePath);
//载入族文件后,再实例化当前功能的主窗口类
MainWindow wpf = new MainWindow();
wpf.Show();//展示界面
return Result.Succeeded;
}
//提取嵌入资源并保存到临时文件路径
private string ExtractEmbeddedResource(string resourceName)
{
//获取程序集
var assembly = this.GetType().Assembly;
//获取临时文件夹路径
string tempPath = Path.GetTempPath();
//生成临时文件名
string tempFileName = Path.GetFileName(resourceName);
string tempFilePath = Path.Combine(tempPath, tempFileName);
//从程序集中提取资源并保存到临时文件
using (Stream resourceStream = assembly.GetManifestResourceStream(resourceName))
{
if (resourceStream == null)
{
throw new FileNotFoundException($"无法找到嵌入的资源: {resourceName}");
}
using (FileStream fileStream = new FileStream(tempFilePath, FileMode.Create))
{
resourceStream.CopyTo(fileStream);
}
}
return tempFilePath;
}
}
}