简体   繁体   中英

How would I load an assembly from the GAC?

I'm trying to use Assembly.Load() to load an assembly that is in the GAC. For example, say I want to list out all of the types that exist in PresentationCore.dll , how would I go about loading PresentationCore.dll ?

When I try this:

Assembly a = Assembly.Load("PresentationCore.dll");

I get a FileNotFoundException . Another answer on SO suggested I used Assembly.LoadFrom() to accomplish this - I'm hesitant to do that because Assembly.LoadFrom() is deprecated, according to Visual Studio 2008 - plus, it doesn't seem to actually work.

Any ideas?

If the assembly is in the GAC you must load it via its fully qualified name.

For example, if I wanted to load mscorlib.dll I would do something like this:

Assembly a = Assembly.Load
    ("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

The easiest way to determine an assembly's fully qualified name is to load the assembly in Reflector and use the Name field from the lower display pane like this:

You need to pass the name of the assembly to Assembly.Load() , not the name of the DLL. If you open the DLL in Reflector, the name should be at the bottom of the window. In the case of PresentationCore.dll, the name should be something like PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 .

I recommend you take a look at How the Runtime Locates Assemblies in the MSDN library to get an idea of what happens when the CLR attempts to load an assembly.

For diagnosing specific issues, the Fusion Log Viewer tool is fantastic. Suzanne Cook, one of the Fusion developers has a guide on her blog which has helped me out in the past.

The easiest way to get the string is to first add a reference to your project then do this:

string regStringMath = typeof(System.Math).Assembly;
Assembly assMath = Assembly.Load("System.Math", regStringMath);

string regStringPres = typeof(PresentationCore).Assembly;
Assembly assPres = Assembly.Load("PresentationCore", regStringPres);

This will ensure you get the right version that you added as a reference to your project.

使用GetAssemblyName( http://msdn.microsoft.com/en-us/library/system.reflection.assemblyname.getassemblyname.aspx )获取dll的完全限定程序集名称,并将其传递给Assembly.Load()。

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