简体   繁体   English

如何使用版本号中的通配符从GAC加载程序集

[英]How to load an assembly from GAC with wildcards in version number

In our application, we have the need to dynamically load 3rd-party assemblies where we do not know in advance all released assembly version numbers. 在我们的应用程序中,我们需要动态加载第三方程序集,而我们事先不知道所有已发布的程序集版本号。 All we know is, for example, that the major version number for the assembly must be "12". 例如,我们所知道的是程序集的主要版本号必须为“ 12”。 On a PC, multiple versions of the same assembly may be installed, having both higher and lower major version numbers. 在PC上,可以安装同一组件的多个版本,同时具有较高和较低的主要版本号。

Ie we would need something like 即我们需要类似的东西

Assembly myAssembly = Assembly.Load("SampleAssembly, Version=12.*.*.*");

and if the assembly versions 11.1.2.3, 12.7.6.5, and 13.9.8.7 are installed, it should load version 12.7.6.5. 如果安装了程序集版本11.1.2.3、12.7.6.5和13.9.8.7,则应加载版本12.7.6.5。

Ie it should be possible to specify wildcards for version number components and it also should be possible to omit Culture and PublicKeyToken . 即,应该可以为版本号组件指定通配符,还可以省略CulturePublicKeyToken When we do this with Assembly.Load() , we get a FileNotFoundException . 当我们使用Assembly.Load()进行此操作时,我们得到一个FileNotFoundException

We cannot use Assembly.LoadWithPartialName() because it always loads the assembly with the highest version number, but we want a specific major version number instead, which possibly is less than the greatest installed assembly version number. 我们不能使用Assembly.LoadWithPartialName()因为它始终以最高版本号加载程序集,但是我们需要一个特定的主版本号,该主版本号可能小于已安装的最大程序集版本号。

Is it possible to do this? 是否有可能做到这一点?

You could manually list the content of the GAC and compare it to your wildcards as so 您可以手动列出GAC的内容,并将其与通配符进行比较

class Program
{
    static void Main(string[] args)
    {
        var assemblyName = "SimpleAssembly";
        var versionRegex = new Regex(@"^12\.");
        var assemblyFile = FindAssemblyFile(assemblyName, versionRegex);

        if (assemblyFile == null)
            throw new FileNotFoundException();

        Assembly.LoadFile(assemblyFile.FullName);
    }

    static FileInfo FindAssemblyFile(string assemblyName, Regex versionRegex)
    {
        var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "assembly", "GAC_MSIL", assemblyName);
        var assemblyDirectory = new DirectoryInfo(path);

        foreach (var versionDirectory in assemblyDirectory.GetDirectories())
        {
            if (versionRegex.IsMatch(versionDirectory.Name))
            {
                return versionDirectory.GetFiles()[0];
            }
        }

        return null;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM