using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.RevitAddIns;
namespace ProceeRvtFile
{
class Program
{
static readonly string[] Searchs =
RevitProductUtility.GetAllInstalledRevitProducts()
.Select(x => x.InstallLocation).ToArray();
static Program()
{
AddEnvironmentPaths(Searchs);
AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;
}
[STAThread]
static void Main(string[] args)
{
Product _product = Product.GetInstalledProduct();
var clientId = new ClientApplicationId(Guid.NewGuid(), "LK", "BIMAPI");
//"I am authorized by Autodesk to use this UI-less functionality."只能为该字符串
_product.Init(clientId, "I am authorized by Autodesk to use this UI-less functionality.");
var Application = _product.Application;
Document doc = Application.OpenDocumentFile("D:/1.rvt");
Console.WriteLine("RVT文件已经打开");
FilteredElementCollector wallCollector = new FilteredElementCollector(doc);
var walls = wallCollector.OfClass(typeof(Wall)).ToArray();
foreach(Wall wall in walls)
{
Console.WriteLine("Wall ElementId:{0}", wall.Id.IntegerValue);
}
doc.Close();
_product?.Exit();
Console.ReadKey(true);
}
static void AddEnvironmentPaths(params string[] paths)
{
var path = new[] { Environment.GetEnvironmentVariable("PATH") ?? string.Empty };
var newPath = string.Join(System.IO.Path.PathSeparator.ToString(), path.Concat(paths));
//设置当前进程中的环境变量
Environment.SetEnvironmentVariable("PATH", newPath);
}
private static Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
{
var assemblyName = new AssemblyName(args.Name);
//在安装路径中查找相关dll并加载
foreach(var item in Searchs)
{
var file = string.Format("{0}.dll", System.IO.Path.Combine(item, assemblyName.Name));
if (File.Exists(file))
{
return Assembly.LoadFile(file);
}
}
return args.RequestingAssembly;
}
}
}
需要引入RevitNET.dll,RevitAddInUtility.dll和RevitAPI.dll三个dll到项目中
有几个问题没有明白:
(1)为什么要设置当前进程的环境变量,如果不设置会提示找不到RevitNET.dll
(2)既然设置了环境变量,那么OnAssemblyResolve的意义何在