简体   繁体   中英

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". On a PC, multiple versions of the same assembly may be installed, having both higher and lower major version numbers.

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.

Ie it should be possible to specify wildcards for version number components and it also should be possible to omit Culture and PublicKeyToken . When we do this with Assembly.Load() , we get a 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.

Is it possible to do this?

You could manually list the content of the GAC and compare it to your wildcards as so

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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