Loading a Program Dynamically with a Display String


Now that you know how to identify an assembly, let's talk about some of the functions that use that information. The .NET framework includes a class called System.Reflection.Assembly. This class does two things: It lets you hold a reference to a loaded assembly, and it provides methods for loading assemblies dynamically. You can load an assembly dynamically using the assembly's display name or using its string path .

To load a program using its display name:

  1. Type System.Reflection.Assembly ad , where ad is the name of the variable to hold a reference to the assembly you're going to load.

  2. Type an equal sign = .

  3. Type System.Reflection.Assembly.Load ( .

  4. Type a display string for the assembly.

  5. Type a close parenthesis, followed by a semicolon ( Figure 12.9 ).

    Figure 12.9 The Load statement uses a display string to locate the assembly. It will look for the assembly in the GAC first. (A number of the examples assume that you have a using System.Reflection; at the top of the code.)
     //using System.Reflection; Assembly ad = Assembly.Load( "SoapSudsCode, Version=1.0.3300.0," + "Culture=neutral, " + "PublicKeyToken=b03f5f7f11d50a3a"); 

graphics/tick.gif Tips

  • The example in Figure 12.9 shows what is called a fully qualified display nameit has all four parts (Assembly name, Version, Culture, and PublicKeyToken). The function works differently if you omit any of the parts, and it will fail if you're trying to locate a DLL in the GAC. However, it's possible to have multiple versions of the same DLL in the GAC, or even multiple cultures. There's another function you can use if you don't know all the parts of the display string. It's called LoadWithPartialName ( Figure 12.10 ).

    Figure 12.10 The GAC can actually store multiple versions of the same assembly. They can do this because the GAC is really a series of subdirectories, and they create a different subdirectory for each version. With Load you have to specify a version number or .NET won't even search the GAC. With LoadWithPartialName you can omit version and have .NET just get the latest version.
     //using System.Reflection; //gets the latest version of the assembly Assembly ad = Assembly.  LoadWithPartialName  ( "SoapSudsCode, Culture=neutral," + "PublicKeyToken=b03f5f7f11d50a3a"); 



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net