【问题标题】:How can I load all dlls from a folder without knowing their names in c# .net?如何在不知道 c# .net 中的名称的情况下从文件夹中加载所有 dll?
【发布时间】:2016-01-18 16:24:58
【问题描述】:

之前我使用这个调用来加载所有从 Rule 类扩展的 cs 文件

var repository = new RuleRepository();
repository.Load(x => x.From(typeof(Rule1).Assembly));

通过调用如上所示的 Load 方法,所有与 Rule1.cs 相同类型的类文件(即从 Rule 类扩展的所有文件)都被加载到存储库内存中。 目前我决定将所有这些 .cs 文件(即 Rule1.cs)转换为 dll 并扫描包含这些 dll 的文件夹。我怎样才能实现这种行为? 目前我正在做这样的事情

Assembly assembly1 = Assembly.LoadFile(Server.MapPath("Rule1.dll"));
List<Assembly> asmblyList = new List<Assembly>();
asmblyList.Add(assembly1);
repository.Load(x => x.From(asmblyList));

我想从文件夹中扫描所有 Rule1.dll 类型的程序集。我怎么可能做到?任何帮助都会很棒。

【问题讨论】:

  • stackoverflow.com/a/20771713/4498937 也许这会有所帮助?
  • @terbubbs 您发布的链接是关于如何在程序集中加载引用的程序集。而我的问题是在不知道名称的情况下加载位于一个文件夹中的所有程序集。让我这样说吧,我只有文件夹的路径,而不是 dll 的名称。如何将该文件夹中的所有 dll 加载到某个列表等中。
  • 我明白你在说什么。让我看看
  • 所以您要加载的 DLL 必须是 Rule1?
  • 从文件夹加载 DLL,我想你可以使用这个解决方案 stackoverflow.com/a/5599581/4498937

标签: c# asp.net .net dll nrules


【解决方案1】:

正如提到的 cmets,获取文件列表并加载它们不是问题,但是只有一种方法可以将加载的程序集删除,即卸载整个 AppDomain。看看这个例子:

static void Main(string[] args)
{
    var path = AssemblyDirectory + @"\external\";
    var files = Directory.GetFiles(path); //get all files

    var ad = AppDomain.CreateDomain("ProbingDomain"); //create another AppDomain
    var tunnel = (AppDomainTunnel)
        ad.CreateInstanceAndUnwrap(typeof (AppDomainTunnel).Assembly.FullName,
        typeof (AppDomainTunnel).FullName); //create tunnel

    var valid = tunnel.GetValidFiles(files); //pass file paths, get valid ones back
    foreach (var file in valid)
    {
        var asm = Assembly.LoadFile(file); //load valid assembly into the main AppDomain
        //do something
    }

    AppDomain.Unload(ad); //unload probing AppDomain
}

private class AppDomainTunnel : MarshalByRefObject 
{   
    public string[] GetValidFiles(string[] files) //this will run in the probing AppDomain
    {
        var valid = new List<string>();
        foreach (var file in files)
        {
            try
            {   //try to load and search for valid types
                var asm = Assembly.LoadFile(file);
                if (asm.GetTypes().Any(x => x.IsSubclassOf(typeof (Rule1))))
                    valid.Add(file); //valid assembly found
            }
            catch (Exception)
            {
                //ignore unloadable files (non .Net, etc.)
            }
        }
        return valid.ToArray();
    }
}
//found here: http://stackoverflow.com/a/283917/4035472
public static string AssemblyDirectory
{
    get
    {
        string codeBase = Assembly.GetExecutingAssembly().CodeBase;
        UriBuilder uri = new UriBuilder(codeBase);
        string path = Uri.UnescapeDataString(uri.Path);
        return Path.GetDirectoryName(path);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 2014-08-10
    • 2023-04-01
    • 2018-02-06
    • 2011-12-16
    • 2022-08-03
    • 1970-01-01
    相关资源
    最近更新 更多