【发布时间】:2010-11-20 06:31:17
【问题描述】:
在 Web 应用程序中,我想加载 /bin 目录中的所有程序集。
由于它可以安装在文件系统的任何位置,我无法保证它的存储路径。
我想要一个汇编程序集对象的列表。
【问题讨论】:
标签: c# assemblies
在 Web 应用程序中,我想加载 /bin 目录中的所有程序集。
由于它可以安装在文件系统的任何位置,我无法保证它的存储路径。
我想要一个汇编程序集对象的列表。
【问题讨论】:
标签: c# assemblies
您可以这样做,但您可能不应该像这样将所有内容加载到当前的应用程序域中,因为程序集可能包含有害代码。
public IEnumerable<Assembly> LoadAssemblies()
{
DirectoryInfo directory = new DirectoryInfo(@"c:\mybinfolder");
FileInfo[] files = directory.GetFiles("*.dll", SearchOption.TopDirectoryOnly);
foreach (FileInfo file in files)
{
// Load the file into the application domain.
AssemblyName assemblyName = AssemblyName.GetAssemblyName(file.FullName);
Assembly assembly = AppDomain.CurrentDomain.Load(assemblyName);
yield return assembly;
}
yield break;
}
编辑:我没有测试代码(在这台计算机上无法访问 Visual Studio),但我希望你能明白。
【讨论】:
好吧,你可以自己用以下方法破解它,最初使用类似的方法:
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 是否实际包含完整路径(如果不包含则连接路径)
【讨论】:
path变量包含目录文件名,需要用Path.GetDirectoryName(path)缩短
要获取 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
}
【讨论】:
我知道这是一个老问题,但是......
System.AppDomain.CurrentDomain.GetAssemblies()
【讨论】: