在Web应用程序中,我想要加载/ bin目录中的所有程序集。如何从/ bin目录中加载所有程序集
由于这可以安装在文件系统的任何位置,因此我无法在它存储的特定路径上进行校准。
我想要一个装配组件对象列表<>。
在Web应用程序中,我想要加载/ bin目录中的所有程序集。如何从/ bin目录中加载所有程序集
由于这可以安装在文件系统的任何位置,因此我无法在它存储的特定路径上进行校准。
我想要一个装配组件对象列表<>。
好了,你可以用下面的方法一起破解这个自己,最初使用类似:
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
获取路径到您当前装配。接下来,使用Directory.GetFiles方法通过合适的过滤器遍历路径中的所有DLL。你的最终代码应该是这样的:
List<Assembly> allAssemblies = new List<Assembly>();
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
foreach (string dll in Directory.GetFiles(path, "*.dll"))
allAssemblies.Add(Assembly.LoadFile(dll));
请注意,我还没有测试,所以你可能需要检查的dll实际上包含完整路径(如果它没有并置路径)
你可以这样做,但你可能不应该像这样加载到当前的应用程序域,因为程序集可能包含有害的代码。编辑:我没有测试代码(在这台计算机没有访问Visual Studio),但我希望你明白了。
要获取bin目录,string path = Assembly.GetExecutingAssembly().Location;
确实不是不是始终有效(特别是执行程序集已放置在ASP.NET临时目录中时)。
相反,你应该使用string binPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "bin");
此外,你应该采取FileLoadException和BadImageFormatException考虑。
这是我的工作职能:
public static void LoadAllBinDirectoryAssemblies()
{
string binPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "bin"); // note: don't use CurrentEntryAssembly or anything like that.
foreach (string dll in Directory.GetFiles(binPath, "*.dll", SearchOption.AllDirectories))
{
try
{
Assembly loadedAssembly = Assembly.LoadFile(dll);
}
catch (FileLoadException loadEx)
{ } // The Assembly has already been loaded.
catch (BadImageFormatException imgEx)
{ } // If a BadImageFormatException exception is thrown, the file is not an assembly.
} // foreach dll
}
“bin”目录不一定会存在于已部署的.NET应用程序中。您应该注意,您的解决方案仅适用于ASP.NET。 – BSick7 2011-06-07 13:56:43
“bin”目录的位置位于AppDomain.SetupInfomation对象中。用法如下: var assembliesDir = setup.PrivateBinPathProbe!= null ? setup.PrivateBinPath:安装程序。ApplicationBase; – 2015-10-06 09:27:56
我知道这是一个老问题,但...
System.AppDomain.CurrentDomain.GetAssemblies()
我相信这只会返回调用程序集引用的程序集(当前程序集依赖的所有程序集)。这并不一定等同于执行目录中的所有程序集。 http://msdn.microsoft.com/en-us/library/system.appdomain.getassemblies.aspx – Jason 2012-11-23 23:37:03
你可能也想添加一个检查以确保你不会添加你实际运行的程序集:) – Wolfwyrd 2009-08-17 15:10:20
'path'变量包含目录文件名,它需要用'Path.GetDirectoryName(path)'缩短 – cjk 2010-07-29 11:28:50
它是已更新以反映上述评论。 – 2013-05-08 21:41:57