如何从/ bin目录中加载所有程序集

mrb*_*lah 39 c# assemblies

在Web应用程序中,我想在/ bin目录中加载所有程序集.

由于这可以安装在文件系统的任何位置,因此我无法保护存储它的特定路径.

我想要一个List <>的Assembly程序集对象.

小智 49

为了得到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
}
Run Code Online (Sandbox Code Playgroud)

  • "bin"目录不一定存在于已部署的.NET应用程序中.您应该注意,您的解决方案仅适用于ASP.NET. (8认同)

Wol*_*yrd 48

好吧,你可以用以下方法自己一起破解,最初使用类似的东西:

string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Run Code Online (Sandbox Code Playgroud)

获取当前程序集的路径.接下来,使用带有合适过滤器的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));
Run Code Online (Sandbox Code Playgroud)

请注意,我没有对此进行测试,因此您可能需要检查dll实际上是否包含完整路径(如果没有,则连接路径)

  • `path`变量包含目录文件名,需要用`Path.GetDirectoryName(path)缩短它. (8认同)
  • 你可能还想添加一个检查,以确保你不添加你实际运行的程序集:) (2认同)

Pat*_*son 6

您可以这样做,但您可能不应该像这样将所有内容加载到当前的appdomain中,因为程序集可能包含有害代码.

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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:我没有测试代码(在这台计算机上无法访问Visual Studio),但我希望你能得到这个想法.