AppDomain.Load AppDomain.Load AppDomain.Load AppDomain.Load Method

Definición

Carga un Assembly en este dominio de aplicación.Loads an Assembly into this application domain.

Sobrecargas

Load(Byte[]) Load(Byte[]) Load(Byte[]) Load(Byte[])

Carga el Assembly con una imagen basada en el formato COFF (Common Object File Format) que contiene un Assembly emitido.Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly.

Load(AssemblyName) Load(AssemblyName) Load(AssemblyName) Load(AssemblyName)

Carga un Assembly a partir de su AssemblyName.Loads an Assembly given its AssemblyName.

Load(String) Load(String) Load(String) Load(String)

Carga un Assembly a partir de su nombre de presentación.Loads an Assembly given its display name.

Load(Byte[], Byte[]) Load(Byte[], Byte[]) Load(Byte[], Byte[]) Load(Byte[], Byte[])

Carga el Assembly con una imagen basada en el formato COFF (Common Object File Format) que contiene un Assembly emitido.Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. También se cargan los bytes sin formato que representan los símbolos del Assembly.The raw bytes representing the symbols for the Assembly are also loaded.

Load(AssemblyName, Evidence) Load(AssemblyName, Evidence) Load(AssemblyName, Evidence) Load(AssemblyName, Evidence)

Carga un Assembly a partir de su AssemblyName.Loads an Assembly given its AssemblyName.

Load(String, Evidence) Load(String, Evidence) Load(String, Evidence) Load(String, Evidence)

Carga un Assembly a partir de su nombre de presentación.Loads an Assembly given its display name.

Load(Byte[], Byte[], Evidence) Load(Byte[], Byte[], Evidence) Load(Byte[], Byte[], Evidence) Load(Byte[], Byte[], Evidence)

Carga el Assembly con una imagen basada en el formato COFF (Common Object File Format) que contiene un Assembly emitido.Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. También se cargan los bytes sin formato que representan los símbolos del Assembly.The raw bytes representing the symbols for the Assembly are also loaded.

Load(Byte[]) Load(Byte[]) Load(Byte[]) Load(Byte[])

Carga el Assembly con una imagen basada en el formato COFF (Common Object File Format) que contiene un Assembly emitido.Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly.

public:
 virtual System::Reflection::Assembly ^ Load(cli::array <System::Byte> ^ rawAssembly);
public System.Reflection.Assembly Load (byte[] rawAssembly);
abstract member Load : byte[] -> System.Reflection.Assembly
override this.Load : byte[] -> System.Reflection.Assembly
Public Function Load (rawAssembly As Byte()) As Assembly

Parámetros

rawAssembly
Byte[]

Matriz de tipo byte que es una imagen basada en COFF que contiene un ensamblado emitido.An array of type byte that is a COFF-based image containing an emitted assembly.

Devoluciones

Ensamblado cargado.The loaded assembly.

Implementaciones

Excepciones

rawAssembly no es un ensamblado válido.rawAssembly is not a valid assembly.

o bien-or- La versión 2.0 u otra posterior de Common Language Runtime está cargada actualmente y rawAssembly se compiló con una versión posterior.Version 2.0 or later of the common language runtime is currently loaded and rawAssembly was compiled with a later version.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

Se cargó un ensamblado o módulo dos veces con dos evidencias diferentes.An assembly or module was loaded twice with two different evidences.

Ejemplos

En el siguiente ejemplo se muestra el uso de la carga de un ensamblado sin formato.The following sample demonstrates the use of loading a raw assembly.

Para que este ejemplo de código se ejecute, debe proporcionar el nombre completo del ensamblado.For this code example to run, you must provide the fully qualified assembly name. Para obtener información sobre cómo obtener el nombre completo del ensamblado, vea nombresde ensamblados.For information about how to obtain the fully qualified assembly name, see Assembly Names.

using namespace System;
using namespace System::IO;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
void InstantiateMyType( AppDomain^ domain )
{
   try
   {
      
      // You must supply a valid fully qualified assembly name here.
      domain->CreateInstance( "Assembly text name, Version, Culture, PublicKeyToken", "MyType" );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( e->Message );
   }

}


// Loads the content of a file to a Byte array.
array<Byte>^ loadFile( String^ filename )
{
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   array<Byte>^buffer = gcnew array<Byte>((int)fs->Length);
   fs->Read( buffer, 0, buffer->Length );
   fs->Close();
   return buffer;
}


// Creates a dynamic assembly with symbol information
// and saves them to temp.dll and temp.pdb
void EmitAssembly( AppDomain^ domain )
{
   AssemblyName^ assemblyName = gcnew AssemblyName;
   assemblyName->Name = "MyAssembly";
   AssemblyBuilder^ assemblyBuilder = domain->DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess::Save );
   ModuleBuilder^ moduleBuilder = assemblyBuilder->DefineDynamicModule( "MyModule", "temp.dll", true );
   TypeBuilder^ typeBuilder = moduleBuilder->DefineType( "MyType", TypeAttributes::Public );
   ConstructorBuilder^ constructorBuilder = typeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, nullptr );
   ILGenerator^ ilGenerator = constructorBuilder->GetILGenerator();
   ilGenerator->EmitWriteLine( "MyType instantiated!" );
   ilGenerator->Emit( OpCodes::Ret );
   typeBuilder->CreateType();
   assemblyBuilder->Save( "temp.dll" );
}

ref class Resolver
{
public:
   static Assembly^ MyResolver( Object^ sender, ResolveEventArgs^ args )
   {
      AppDomain^ domain = dynamic_cast<AppDomain^>(sender);
      
      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly( domain );
      array<Byte>^rawAssembly = loadFile( "temp.dll" );
      array<Byte>^rawSymbolStore = loadFile( "temp.pdb" );
      Assembly^ assembly = domain->Load( rawAssembly, rawSymbolStore );
      return assembly;
   }

};

int main()
{
   AppDomain^ currentDomain = AppDomain::CurrentDomain;
   InstantiateMyType( currentDomain ); // Failed!
   currentDomain->AssemblyResolve += gcnew ResolveEventHandler( Resolver::MyResolver );
   InstantiateMyType( currentDomain ); // OK!
}

using System;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      
      InstantiateMyType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolver);
      
      InstantiateMyType(currentDomain);   // OK!
   }
   
   static void InstantiateMyType(AppDomain domain) {
      try {
	 // You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }
   
   // Loads the content of a file to a byte array. 
   static byte[] loadFile(string filename) {
      FileStream fs = new FileStream(filename, FileMode.Open);
      byte[] buffer = new byte[(int) fs.Length];
      fs.Read(buffer, 0, buffer.Length);
      fs.Close();
   
      return buffer;
   }   

   static Assembly MyResolver(object sender, ResolveEventArgs args) {
      AppDomain domain = (AppDomain) sender;

      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly(domain);
      
      byte[] rawAssembly = loadFile("temp.dll");
      byte[] rawSymbolStore = loadFile("temp.pdb");
      Assembly assembly = domain.Load(rawAssembly, rawSymbolStore);

      return assembly;
   }
   
   // Creates a dynamic assembly with symbol information
   // and saves them to temp.dll and temp.pdb
   static void EmitAssembly(AppDomain domain) {
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", true);
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public);

      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      ilGenerator.EmitWriteLine("MyType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();
      
      assemblyBuilder.Save("temp.dll");
   }
}
Imports System
Imports System.IO
Imports System.Reflection
Imports System.Reflection.Emit

Module Test
   
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      
      InstantiateMyType(currentDomain)      ' Failed!

      AddHandler currentDomain.AssemblyResolve, AddressOf MyResolver
      
      InstantiateMyType(currentDomain)      ' OK!
   End Sub 'Main
   
   
   Sub InstantiateMyType(domain As AppDomain)
      Try
	 ' You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType")
      Catch e As Exception
         Console.WriteLine(e.Message)
      End Try
   End Sub 'InstantiateMyType
   
   
   ' Loads the content of a file to a byte array. 
   Function loadFile(filename As String) As Byte()
      Dim fs As New FileStream(filename, FileMode.Open)
      Dim buffer(CInt(fs.Length)) As Byte
      fs.Read(buffer, 0, buffer.Length)
      fs.Close()
      
      Return buffer
   End Function 'loadFile
   
   
   Function MyResolver(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
      Dim domain As AppDomain = DirectCast(sender, AppDomain)
      
      ' Once the files are generated, this call is
      ' actually no longer necessary.
      EmitAssembly(domain)
      
      Dim rawAssembly As Byte() = loadFile("temp.dll")
      Dim rawSymbolStore As Byte() = loadFile("temp.pdb")
      Dim myAssembly As System.Reflection.Assembly = domain.Load(rawAssembly, rawSymbolStore)
      
      Return myAssembly
   End Function 'MyResolver
   
   
   ' Creates a dynamic assembly with symbol information
   ' and saves them to temp.dll and temp.pdb
   Sub EmitAssembly(domain As AppDomain)
      Dim assemblyName As New AssemblyName()
      assemblyName.Name = "MyAssembly"
      
      Dim assemblyBuilder As AssemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save)
      Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", True)
      Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public)
      
      Dim constructorBuilder As ConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Nothing)
      Dim ilGenerator As ILGenerator = constructorBuilder.GetILGenerator()
      ilGenerator.EmitWriteLine("MyType instantiated!")
      ilGenerator.Emit(OpCodes.Ret)
      
      typeBuilder.CreateType()
      
      assemblyBuilder.Save("temp.dll")
   End Sub 'EmitAssembly

End Module 'Test

Comentarios

A partir de .NET Framework 4.NET Framework 4, el nivel de confianza de un ensamblado que se carga mediante este método es el mismo que el nivel de confianza del dominio de aplicación.Beginning with the .NET Framework 4.NET Framework 4, the trust level of an assembly that is loaded by using this method is the same as the trust level of the application domain.

Este método solo se debe usar para cargar un ensamblado en el dominio de aplicación actual.This method should be used only to load an assembly into the current application domain. Este método se proporciona por comodidad para los llamadores de interoperabilidad que no pueden Assembly.Load llamar al método estático.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Para cargar ensamblados en otros dominios de aplicación, use un método CreateInstanceAndUnwrapcomo.To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Para obtener información común a todas las sobrecargas de este método, vea la Load(AssemblyName) sobrecarga del método.For information that is common to all overloads of this method, see the Load(AssemblyName) method overload.

Seguridad

FileIOPermission
para el acceso para leer desde un archivo o un directorio, y para tener acceso a la información de la propia ruta de acceso.for access to read from a file or directory, and for access to the information in the path itself. Enumeraciones asociadas: Read, PathDiscovery.Associated enumerations: Read, PathDiscovery.

Load(AssemblyName) Load(AssemblyName) Load(AssemblyName) Load(AssemblyName)

Carga un Assembly a partir de su AssemblyName.Loads an Assembly given its AssemblyName.

public:
 virtual System::Reflection::Assembly ^ Load(System::Reflection::AssemblyName ^ assemblyRef);
public System.Reflection.Assembly Load (System.Reflection.AssemblyName assemblyRef);
abstract member Load : System.Reflection.AssemblyName -> System.Reflection.Assembly
override this.Load : System.Reflection.AssemblyName -> System.Reflection.Assembly
Public Function Load (assemblyRef As AssemblyName) As Assembly

Parámetros

assemblyRef
AssemblyName AssemblyName AssemblyName AssemblyName

Objeto que describe el ensamblado que se va a cargar.An object that describes the assembly to load.

Devoluciones

Ensamblado cargado.The loaded assembly.

Implementaciones

Excepciones

No se ha encontrado assemblyRef.assemblyRef is not found.

assemblyRef no es un ensamblado válido.assemblyRef is not a valid assembly.

o bien-or- La versión 2.0 u otra posterior de Common Language Runtime está cargada actualmente y assemblyRef se compiló con una versión posterior.Version 2.0 or later of the common language runtime is currently loaded and assemblyRef was compiled with a later version.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

Se cargó un ensamblado o módulo dos veces con dos evidencias diferentes.An assembly or module was loaded twice with two different evidences.

Comentarios

Este método solo se debe usar para cargar un ensamblado en el dominio de aplicación actual.This method should be used only to load an assembly into the current application domain. Este método se proporciona por comodidad para los llamadores de interoperabilidad que no pueden Assembly.Load llamar al método estático.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Para cargar ensamblados en otros dominios de aplicación, use un método CreateInstanceAndUnwrapcomo.To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Si ya se ha cargado una versión del ensamblado solicitado, este método devuelve el ensamblado cargado, aunque se solicite una versión diferente.If a version of the requested assembly is already loaded, this method returns the loaded assembly, even if a different version is requested.

No se recomienda proporcionar un nombre assemblyRef de ensamblado parcial para.Supplying a partial assembly name for assemblyRef is not recommended. (Un nombre parcial omite uno o varios de los tokens de referencia cultural, versión o clave pública.(A partial name omits one or more of culture, version, or public key token. En el caso de las sobrecargas que toman una cadena AssemblyName en lugar de un objeto, "myAssembly, version = 1.0.0.0" es un ejemplo de un nombre parcial y "myAssembly, version = 1.0.0.0, Culture = neutral, PublicKeyToken = 18ab3442da84b47" es un ejemplo de un nombre completo). El uso de nombres parciales tiene un efecto negativo en el rendimiento.For overloads that take a string instead of an AssemblyName object, "MyAssembly, Version=1.0.0.0" is an example of a partial name and "MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=18ab3442da84b47" is an example of a full name.) Using partial names has a negative effect on performance. Además, un nombre de ensamblado parcial solo puede cargar un ensamblado de la caché global de ensamblados si hay una copia exacta del ensamblado en el directorioBaseDirectory base AppDomainSetup.ApplicationBasede la aplicación (o).In addition, a partial assembly name can load an assembly from the global assembly cache only if there is an exact copy of the assembly in the application base directory (BaseDirectory or AppDomainSetup.ApplicationBase).

Si el objeto AppDomain actual representa el dominio Ade aplicación y Load se llama al método desde el Bdominio de aplicación, el ensamblado se carga en ambos dominios de aplicación.If the current AppDomain object represents application domain A, and the Load method is called from application domain B, the assembly is loaded into both application domains. Por ejemplo, el código siguiente se MyAssembly carga en el nuevo dominio ChildDomain de aplicación y también en el dominio de aplicación donde se ejecuta el código:For example, the following code loads MyAssembly into the new application domain ChildDomain and also into the application domain where the code executes:

AppDomain^ ad = AppDomain::CreateDomain("ChildDomain");
ad->Load("MyAssembly");
AppDomain ad = AppDomain.CreateDomain("ChildDomain");
ad.Load("MyAssembly");
Dim ad As AppDomain  = AppDomain.CreateDomain("ChildDomain")
ad.Load("MyAssembly")

El ensamblado se carga en ambos dominios Assembly porque no se deriva MarshalByRefObjectde y, por tanto, no se Load pueden calcular las referencias del valor devuelto del método.The assembly is loaded into both domains because Assembly does not derive from MarshalByRefObject, and therefore the return value of the Load method cannot be marshaled. En su lugar, el Common Language Runtime intenta cargar el ensamblado en el dominio de aplicación que realiza la llamada.Instead, the common language runtime tries to load the assembly into the calling application domain. Los ensamblados que se cargan en los dos dominios de aplicación pueden ser diferentes si la configuración de la ruta de acceso de los dos dominios de aplicación es diferente.The assemblies that are loaded into the two application domains might be different if the path settings for the two application domains are different.

Nota

Si se establecen AssemblyName.Name tanto la propiedad AssemblyName.CodeBase como la propiedad, el primer intento de cargar el ensamblado usa el nombre para mostrar (incluida la versión, la referencia cultural, etc., Assembly.FullName tal y como lo devuelve la propiedad).If both the AssemblyName.Name property and the AssemblyName.CodeBase property are set, the first attempt to load the assembly uses the display name (including version, culture, and so on, as returned by the Assembly.FullName property). Si no se encuentra el archivo, la CodeBase propiedad se usa para buscar el ensamblado.If the file is not found, the CodeBase property is used to search for the assembly. Si se encuentra el ensamblado CodeBasemediante, el nombre para mostrar coincide con el ensamblado.If the assembly is found using CodeBase, the display name is matched against the assembly. Si se produce un error en FileLoadException la coincidencia, se produce una excepción.If the match fails, a FileLoadException is thrown.

Seguridad

FileIOPermission
para el acceso para leer desde un archivo o un directorio, y para tener acceso a la información de la propia ruta de acceso.for access to read from a file or directory, and for access to the information in the path itself. Enumeraciones asociadas: Read, PathDiscovery.Associated enumerations: Read, PathDiscovery.

Load(String) Load(String) Load(String) Load(String)

Carga un Assembly a partir de su nombre de presentación.Loads an Assembly given its display name.

public:
 virtual System::Reflection::Assembly ^ Load(System::String ^ assemblyString);
public System.Reflection.Assembly Load (string assemblyString);
abstract member Load : string -> System.Reflection.Assembly
override this.Load : string -> System.Reflection.Assembly
Public Function Load (assemblyString As String) As Assembly

Parámetros

assemblyString
String String String String

Nombre para mostrar del ensamblado.The display name of the assembly. Vea FullName.See FullName.

Devoluciones

Ensamblado cargado.The loaded assembly.

Implementaciones

Excepciones

assemblyString no es un ensamblado válido.assemblyString is not a valid assembly.

O bien-or- La versión 2.0 u otra posterior de Common Language Runtime está cargada actualmente y assemblyString se compiló con una versión posterior.Version 2.0 or later of the common language runtime is currently loaded and assemblyString was compiled with a later version.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

Se cargó un ensamblado o módulo dos veces con dos evidencias diferentes.An assembly or module was loaded twice with two different evidences.

Comentarios

Este método solo se debe usar para cargar un ensamblado en el dominio de aplicación actual.This method should be used only to load an assembly into the current application domain. Este método se proporciona por comodidad para los llamadores de interoperabilidad que no pueden Assembly.Load llamar al método estático.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Para cargar ensamblados en otros dominios de aplicación, use un método CreateInstanceAndUnwrapcomo.To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Para obtener información común a todas las sobrecargas de este método, vea la Load(AssemblyName) sobrecarga del método.For information that is common to all overloads of this method, see the Load(AssemblyName) method overload.

Seguridad

FileIOPermission
para el acceso para leer desde un archivo o un directorio, y para tener acceso a la información de la propia ruta de acceso.for access to read from a file or directory, and for access to the information in the path itself. Enumeraciones asociadas: Read, PathDiscovery.Associated enumerations: Read, PathDiscovery.

WebPermission
permite tener acceso a la ubicación del ensamblado si el ensamblado no es local.for the ability to access the location of the assembly if the assembly is not local.

Load(Byte[], Byte[]) Load(Byte[], Byte[]) Load(Byte[], Byte[]) Load(Byte[], Byte[])

Carga el Assembly con una imagen basada en el formato COFF (Common Object File Format) que contiene un Assembly emitido.Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. También se cargan los bytes sin formato que representan los símbolos del Assembly.The raw bytes representing the symbols for the Assembly are also loaded.

public:
 virtual System::Reflection::Assembly ^ Load(cli::array <System::Byte> ^ rawAssembly, cli::array <System::Byte> ^ rawSymbolStore);
public System.Reflection.Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore);
abstract member Load : byte[] * byte[] -> System.Reflection.Assembly
override this.Load : byte[] * byte[] -> System.Reflection.Assembly
Public Function Load (rawAssembly As Byte(), rawSymbolStore As Byte()) As Assembly

Parámetros

rawAssembly
Byte[]

Matriz de tipo byte que es una imagen basada en COFF que contiene un ensamblado emitido.An array of type byte that is a COFF-based image containing an emitted assembly.

rawSymbolStore
Byte[]

Matriz de tipo byte que contiene los bytes sin formato que representan los símbolos del ensamblado.An array of type byte containing the raw bytes representing the symbols for the assembly.

Devoluciones

Ensamblado cargado.The loaded assembly.

Implementaciones

Excepciones

rawAssembly no es un ensamblado válido.rawAssembly is not a valid assembly.

o bien-or- La versión 2.0 u otra posterior de Common Language Runtime está cargada actualmente y rawAssembly se compiló con una versión posterior.Version 2.0 or later of the common language runtime is currently loaded and rawAssembly was compiled with a later version.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

Se cargó un ensamblado o módulo dos veces con dos evidencias diferentes.An assembly or module was loaded twice with two different evidences.

Ejemplos

En el siguiente ejemplo se muestra el uso de la carga de un ensamblado sin formato.The following sample demonstrates the use of loading a raw assembly.

Para que este ejemplo de código se ejecute, debe proporcionar el nombre completo del ensamblado.For this code example to run, you must provide the fully qualified assembly name. Para obtener información sobre cómo obtener el nombre completo del ensamblado, vea nombresde ensamblados.For information about how to obtain the fully qualified assembly name, see Assembly Names.

using namespace System;
using namespace System::IO;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
void InstantiateMyType( AppDomain^ domain )
{
   try
   {
      
      // You must supply a valid fully qualified assembly name here.
      domain->CreateInstance( "Assembly text name, Version, Culture, PublicKeyToken", "MyType" );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( e->Message );
   }

}


// Loads the content of a file to a Byte array.
array<Byte>^ loadFile( String^ filename )
{
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   array<Byte>^buffer = gcnew array<Byte>((int)fs->Length);
   fs->Read( buffer, 0, buffer->Length );
   fs->Close();
   return buffer;
}


// Creates a dynamic assembly with symbol information
// and saves them to temp.dll and temp.pdb
void EmitAssembly( AppDomain^ domain )
{
   AssemblyName^ assemblyName = gcnew AssemblyName;
   assemblyName->Name = "MyAssembly";
   AssemblyBuilder^ assemblyBuilder = domain->DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess::Save );
   ModuleBuilder^ moduleBuilder = assemblyBuilder->DefineDynamicModule( "MyModule", "temp.dll", true );
   TypeBuilder^ typeBuilder = moduleBuilder->DefineType( "MyType", TypeAttributes::Public );
   ConstructorBuilder^ constructorBuilder = typeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, nullptr );
   ILGenerator^ ilGenerator = constructorBuilder->GetILGenerator();
   ilGenerator->EmitWriteLine( "MyType instantiated!" );
   ilGenerator->Emit( OpCodes::Ret );
   typeBuilder->CreateType();
   assemblyBuilder->Save( "temp.dll" );
}

ref class Resolver
{
public:
   static Assembly^ MyResolver( Object^ sender, ResolveEventArgs^ args )
   {
      AppDomain^ domain = dynamic_cast<AppDomain^>(sender);
      
      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly( domain );
      array<Byte>^rawAssembly = loadFile( "temp.dll" );
      array<Byte>^rawSymbolStore = loadFile( "temp.pdb" );
      Assembly^ assembly = domain->Load( rawAssembly, rawSymbolStore );
      return assembly;
   }

};

int main()
{
   AppDomain^ currentDomain = AppDomain::CurrentDomain;
   InstantiateMyType( currentDomain ); // Failed!
   currentDomain->AssemblyResolve += gcnew ResolveEventHandler( Resolver::MyResolver );
   InstantiateMyType( currentDomain ); // OK!
}

using System;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      
      InstantiateMyType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolver);
      
      InstantiateMyType(currentDomain);   // OK!
   }
   
   static void InstantiateMyType(AppDomain domain) {
      try {
	 // You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }
   
   // Loads the content of a file to a byte array. 
   static byte[] loadFile(string filename) {
      FileStream fs = new FileStream(filename, FileMode.Open);
      byte[] buffer = new byte[(int) fs.Length];
      fs.Read(buffer, 0, buffer.Length);
      fs.Close();
   
      return buffer;
   }   

   static Assembly MyResolver(object sender, ResolveEventArgs args) {
      AppDomain domain = (AppDomain) sender;

      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly(domain);
      
      byte[] rawAssembly = loadFile("temp.dll");
      byte[] rawSymbolStore = loadFile("temp.pdb");
      Assembly assembly = domain.Load(rawAssembly, rawSymbolStore);

      return assembly;
   }
   
   // Creates a dynamic assembly with symbol information
   // and saves them to temp.dll and temp.pdb
   static void EmitAssembly(AppDomain domain) {
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", true);
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public);

      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      ilGenerator.EmitWriteLine("MyType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();
      
      assemblyBuilder.Save("temp.dll");
   }
}
Imports System
Imports System.IO
Imports System.Reflection
Imports System.Reflection.Emit

Module Test
   
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      
      InstantiateMyType(currentDomain)      ' Failed!

      AddHandler currentDomain.AssemblyResolve, AddressOf MyResolver
      
      InstantiateMyType(currentDomain)      ' OK!
   End Sub 'Main
   
   
   Sub InstantiateMyType(domain As AppDomain)
      Try
	 ' You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType")
      Catch e As Exception
         Console.WriteLine(e.Message)
      End Try
   End Sub 'InstantiateMyType
   
   
   ' Loads the content of a file to a byte array. 
   Function loadFile(filename As String) As Byte()
      Dim fs As New FileStream(filename, FileMode.Open)
      Dim buffer(CInt(fs.Length)) As Byte
      fs.Read(buffer, 0, buffer.Length)
      fs.Close()
      
      Return buffer
   End Function 'loadFile
   
   
   Function MyResolver(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
      Dim domain As AppDomain = DirectCast(sender, AppDomain)
      
      ' Once the files are generated, this call is
      ' actually no longer necessary.
      EmitAssembly(domain)
      
      Dim rawAssembly As Byte() = loadFile("temp.dll")
      Dim rawSymbolStore As Byte() = loadFile("temp.pdb")
      Dim myAssembly As System.Reflection.Assembly = domain.Load(rawAssembly, rawSymbolStore)
      
      Return myAssembly
   End Function 'MyResolver
   
   
   ' Creates a dynamic assembly with symbol information
   ' and saves them to temp.dll and temp.pdb
   Sub EmitAssembly(domain As AppDomain)
      Dim assemblyName As New AssemblyName()
      assemblyName.Name = "MyAssembly"
      
      Dim assemblyBuilder As AssemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save)
      Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", True)
      Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public)
      
      Dim constructorBuilder As ConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Nothing)
      Dim ilGenerator As ILGenerator = constructorBuilder.GetILGenerator()
      ilGenerator.EmitWriteLine("MyType instantiated!")
      ilGenerator.Emit(OpCodes.Ret)
      
      typeBuilder.CreateType()
      
      assemblyBuilder.Save("temp.dll")
   End Sub 'EmitAssembly

End Module 'Test

Comentarios

A partir de .NET Framework 4.NET Framework 4, el nivel de confianza de un ensamblado que se carga mediante este método es el mismo que el nivel de confianza del dominio de aplicación.Beginning with the .NET Framework 4.NET Framework 4, the trust level of an assembly that is loaded by using this method is the same as the trust level of the application domain.

Este método solo se debe usar para cargar un ensamblado en el dominio de aplicación actual.This method should be used only to load an assembly into the current application domain. Este método se proporciona por comodidad para los llamadores de interoperabilidad que no pueden Assembly.Load llamar al método estático.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Para cargar ensamblados en otros dominios de aplicación, use un método CreateInstanceAndUnwrapcomo.To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Para obtener información común a todas las sobrecargas de este método, vea la Load(AssemblyName) sobrecarga del método.For information that is common to all overloads of this method, see the Load(AssemblyName) method overload.

Seguridad

WebPermission
para leer un URI que no comienza por "file://".for reading a URI that does not begin with "file://".

FileIOPermission
para el acceso para leer desde un archivo o un directorio, y para tener acceso a la información de la propia ruta de acceso.for access to read from a file or directory, and for access to the information in the path itself. Enumeraciones asociadas: Read, PathDiscovery.Associated enumerations: Read, PathDiscovery.

Load(AssemblyName, Evidence) Load(AssemblyName, Evidence) Load(AssemblyName, Evidence) Load(AssemblyName, Evidence)

Advertencia

Esta API está ya obsoleta.

Carga un Assembly a partir de su AssemblyName.Loads an Assembly given its AssemblyName.

public:
 virtual System::Reflection::Assembly ^ Load(System::Reflection::AssemblyName ^ assemblyRef, System::Security::Policy::Evidence ^ assemblySecurity);
[System.Obsolete("Use an overload that does not take an Evidence parameter")]
[System.Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public System.Reflection.Assembly Load (System.Reflection.AssemblyName assemblyRef, System.Security.Policy.Evidence assemblySecurity);
abstract member Load : System.Reflection.AssemblyName * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : System.Reflection.AssemblyName * System.Security.Policy.Evidence -> System.Reflection.Assembly
Public Function Load (assemblyRef As AssemblyName, assemblySecurity As Evidence) As Assembly

Parámetros

assemblyRef
AssemblyName AssemblyName AssemblyName AssemblyName

Objeto que describe el ensamblado que se va a cargar.An object that describes the assembly to load.

assemblySecurity
Evidence Evidence Evidence Evidence

Evidencia para cargar el ensamblado.Evidence for loading the assembly.

Devoluciones

Ensamblado cargado.The loaded assembly.

Implementaciones

Excepciones

assemblyRef no es un ensamblado válido.assemblyRef is not a valid assembly.

o bien-or- La versión 2.0 u otra posterior de Common Language Runtime está cargada actualmente y assemblyRef se compiló con una versión posterior.Version 2.0 or later of the common language runtime is currently loaded and assemblyRef was compiled with a later version.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

Se cargó un ensamblado o módulo dos veces con dos evidencias diferentes.An assembly or module was loaded twice with two different evidences.

Comentarios

Este método solo se debe usar para cargar un ensamblado en el dominio de aplicación actual.This method should be used only to load an assembly into the current application domain. Este método se proporciona por comodidad para los llamadores de interoperabilidad que no pueden Assembly.Load llamar al método estático.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Para cargar ensamblados en otros dominios de aplicación, use un método CreateInstanceAndUnwrapcomo.To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Para obtener información común a todas las sobrecargas de este método, vea la Load(AssemblyName) sobrecarga del método.For information that is common to all overloads of this method, see the Load(AssemblyName) method overload.

Seguridad

FileIOPermission
para el acceso para leer desde un archivo o un directorio, y para tener acceso a la información de la propia ruta de acceso.for access to read from a file or directory, and for access to the information in the path itself. Enumeraciones asociadas: Read, PathDiscovery.Associated enumerations: Read, PathDiscovery.

SecurityPermission
para cargar un ensamblado con evidencia.to load an assembly with evidence. Enumeración asociada: ControlEvidence.Associated enumeration: ControlEvidence.

WebPermission
para leer una ruta de acceso que no tiene el formato "File://" o\\"\\\UNC\dir" o "c\\:".for reading a path that is not in the form "file://" or "\\\UNC\dir\\" or "c:\\".

Load(String, Evidence) Load(String, Evidence) Load(String, Evidence) Load(String, Evidence)

Advertencia

Esta API está ya obsoleta.

Carga un Assembly a partir de su nombre de presentación.Loads an Assembly given its display name.

public:
 virtual System::Reflection::Assembly ^ Load(System::String ^ assemblyString, System::Security::Policy::Evidence ^ assemblySecurity);
[System.Obsolete("Use an overload that does not take an Evidence parameter")]
[System.Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public System.Reflection.Assembly Load (string assemblyString, System.Security.Policy.Evidence assemblySecurity);
abstract member Load : string * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : string * System.Security.Policy.Evidence -> System.Reflection.Assembly
Public Function Load (assemblyString As String, assemblySecurity As Evidence) As Assembly

Parámetros

assemblyString
String String String String

Nombre para mostrar del ensamblado.The display name of the assembly. Vea FullName.See FullName.

assemblySecurity
Evidence Evidence Evidence Evidence

Evidencia para cargar el ensamblado.Evidence for loading the assembly.

Devoluciones

Ensamblado cargado.The loaded assembly.

Implementaciones

Excepciones

assemblyString no es un ensamblado válido.assemblyString is not a valid assembly.

O bien-or- La versión 2.0 u otra posterior de Common Language Runtime está cargada actualmente y assemblyString se compiló con una versión posterior.Version 2.0 or later of the common language runtime is currently loaded and assemblyString was compiled with a later version.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

Se cargó un ensamblado o módulo dos veces con dos evidencias diferentes.An assembly or module was loaded twice with two different evidences.

Comentarios

Este método solo se debe usar para cargar un ensamblado en el dominio de aplicación actual.This method should be used only to load an assembly into the current application domain. Este método se proporciona por comodidad para los llamadores de interoperabilidad que no pueden Assembly.Load llamar al método estático.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Para cargar ensamblados en otros dominios de aplicación, use un método CreateInstanceAndUnwrapcomo.To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Para obtener información común a todas las sobrecargas de este método, vea la Load(AssemblyName) sobrecarga del método.For information that is common to all overloads of this method, see the Load(AssemblyName) method overload.

Seguridad

SecurityPermission
para cargar un ensamblado con evidencia.to load an assembly with evidence. Enumeración asociada: ControlEvidence.Associated enumeration: ControlEvidence.

FileIOPermission
para el acceso para leer desde un archivo o un directorio, y para tener acceso a la información de la propia ruta de acceso.for access to read from a file or directory, and for access to the information in the path itself. Enumeraciones asociadas: Read, PathDiscovery.Associated enumerations: Read, PathDiscovery.

WebPermission
para leer una ruta de acceso que no tiene el formato "File://" o\\"\\\UNC\dir" o "c\\:".for reading a path that is not in the form "file://" or "\\\UNC\dir\\" or "c:\\".

Load(Byte[], Byte[], Evidence) Load(Byte[], Byte[], Evidence) Load(Byte[], Byte[], Evidence) Load(Byte[], Byte[], Evidence)

Advertencia

Esta API está ya obsoleta.

Carga el Assembly con una imagen basada en el formato COFF (Common Object File Format) que contiene un Assembly emitido.Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. También se cargan los bytes sin formato que representan los símbolos del Assembly.The raw bytes representing the symbols for the Assembly are also loaded.

public:
 virtual System::Reflection::Assembly ^ Load(cli::array <System::Byte> ^ rawAssembly, cli::array <System::Byte> ^ rawSymbolStore, System::Security::Policy::Evidence ^ securityEvidence);
[System.Obsolete("Use an overload that does not take an Evidence parameter")]
[System.Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkId=155570 for more information.")]
public System.Reflection.Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, System.Security.Policy.Evidence securityEvidence);
abstract member Load : byte[] * byte[] * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : byte[] * byte[] * System.Security.Policy.Evidence -> System.Reflection.Assembly
Public Function Load (rawAssembly As Byte(), rawSymbolStore As Byte(), securityEvidence As Evidence) As Assembly

Parámetros

rawAssembly
Byte[]

Matriz de tipo byte que es una imagen basada en COFF que contiene un ensamblado emitido.An array of type byte that is a COFF-based image containing an emitted assembly.

rawSymbolStore
Byte[]

Matriz de tipo byte que contiene los bytes sin formato que representan los símbolos del ensamblado.An array of type byte containing the raw bytes representing the symbols for the assembly.

securityEvidence
Evidence Evidence Evidence Evidence

Evidencia para cargar el ensamblado.Evidence for loading the assembly.

Devoluciones

Ensamblado cargado.The loaded assembly.

Implementaciones

Excepciones

rawAssembly no es un ensamblado válido.rawAssembly is not a valid assembly.

O bien-or- La versión 2.0 u otra posterior de Common Language Runtime está cargada actualmente y rawAssembly se compiló con una versión posterior.Version 2.0 or later of the common language runtime is currently loaded and rawAssembly was compiled with a later version.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

Se cargó un ensamblado o módulo dos veces con dos evidencias diferentes.An assembly or module was loaded twice with two different evidences.

securityEvidence no es null.securityEvidence is not null. Cuando no se habilita la directiva CAS heredada, securityEvidence debe ser null.When legacy CAS policy is not enabled, securityEvidence should be null.

Ejemplos

En el siguiente ejemplo se muestra el uso de la carga de un ensamblado sin formato.The following sample demonstrates the use of loading a raw assembly.

Para que este ejemplo de código se ejecute, debe proporcionar el nombre completo del ensamblado.For this code example to run, you must provide the fully qualified assembly name. Para obtener información sobre cómo obtener el nombre completo del ensamblado, vea nombresde ensamblados.For information about how to obtain the fully qualified assembly name, see Assembly Names.

using namespace System;
using namespace System::IO;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
void InstantiateMyType( AppDomain^ domain )
{
   try
   {
      
      // You must supply a valid fully qualified assembly name here.
      domain->CreateInstance( "Assembly text name, Version, Culture, PublicKeyToken", "MyType" );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( e->Message );
   }

}


// Loads the content of a file to a Byte array.
array<Byte>^ loadFile( String^ filename )
{
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   array<Byte>^buffer = gcnew array<Byte>((int)fs->Length);
   fs->Read( buffer, 0, buffer->Length );
   fs->Close();
   return buffer;
}


// Creates a dynamic assembly with symbol information
// and saves them to temp.dll and temp.pdb
void EmitAssembly( AppDomain^ domain )
{
   AssemblyName^ assemblyName = gcnew AssemblyName;
   assemblyName->Name = "MyAssembly";
   AssemblyBuilder^ assemblyBuilder = domain->DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess::Save );
   ModuleBuilder^ moduleBuilder = assemblyBuilder->DefineDynamicModule( "MyModule", "temp.dll", true );
   TypeBuilder^ typeBuilder = moduleBuilder->DefineType( "MyType", TypeAttributes::Public );
   ConstructorBuilder^ constructorBuilder = typeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, nullptr );
   ILGenerator^ ilGenerator = constructorBuilder->GetILGenerator();
   ilGenerator->EmitWriteLine( "MyType instantiated!" );
   ilGenerator->Emit( OpCodes::Ret );
   typeBuilder->CreateType();
   assemblyBuilder->Save( "temp.dll" );
}

ref class Resolver
{
public:
   static Assembly^ MyResolver( Object^ sender, ResolveEventArgs^ args )
   {
      AppDomain^ domain = dynamic_cast<AppDomain^>(sender);
      
      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly( domain );
      array<Byte>^rawAssembly = loadFile( "temp.dll" );
      array<Byte>^rawSymbolStore = loadFile( "temp.pdb" );
      Assembly^ assembly = domain->Load( rawAssembly, rawSymbolStore );
      return assembly;
   }

};

int main()
{
   AppDomain^ currentDomain = AppDomain::CurrentDomain;
   InstantiateMyType( currentDomain ); // Failed!
   currentDomain->AssemblyResolve += gcnew ResolveEventHandler( Resolver::MyResolver );
   InstantiateMyType( currentDomain ); // OK!
}

using System;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      
      InstantiateMyType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolver);
      
      InstantiateMyType(currentDomain);   // OK!
   }
   
   static void InstantiateMyType(AppDomain domain) {
      try {
	 // You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }
   
   // Loads the content of a file to a byte array. 
   static byte[] loadFile(string filename) {
      FileStream fs = new FileStream(filename, FileMode.Open);
      byte[] buffer = new byte[(int) fs.Length];
      fs.Read(buffer, 0, buffer.Length);
      fs.Close();
   
      return buffer;
   }   

   static Assembly MyResolver(object sender, ResolveEventArgs args) {
      AppDomain domain = (AppDomain) sender;

      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly(domain);
      
      byte[] rawAssembly = loadFile("temp.dll");
      byte[] rawSymbolStore = loadFile("temp.pdb");
      Assembly assembly = domain.Load(rawAssembly, rawSymbolStore);

      return assembly;
   }
   
   // Creates a dynamic assembly with symbol information
   // and saves them to temp.dll and temp.pdb
   static void EmitAssembly(AppDomain domain) {
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", true);
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public);

      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      ilGenerator.EmitWriteLine("MyType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();
      
      assemblyBuilder.Save("temp.dll");
   }
}
Imports System
Imports System.IO
Imports System.Reflection
Imports System.Reflection.Emit

Module Test
   
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      
      InstantiateMyType(currentDomain)      ' Failed!

      AddHandler currentDomain.AssemblyResolve, AddressOf MyResolver
      
      InstantiateMyType(currentDomain)      ' OK!
   End Sub 'Main
   
   
   Sub InstantiateMyType(domain As AppDomain)
      Try
	 ' You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType")
      Catch e As Exception
         Console.WriteLine(e.Message)
      End Try
   End Sub 'InstantiateMyType
   
   
   ' Loads the content of a file to a byte array. 
   Function loadFile(filename As String) As Byte()
      Dim fs As New FileStream(filename, FileMode.Open)
      Dim buffer(CInt(fs.Length)) As Byte
      fs.Read(buffer, 0, buffer.Length)
      fs.Close()
      
      Return buffer
   End Function 'loadFile
   
   
   Function MyResolver(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
      Dim domain As AppDomain = DirectCast(sender, AppDomain)
      
      ' Once the files are generated, this call is
      ' actually no longer necessary.
      EmitAssembly(domain)
      
      Dim rawAssembly As Byte() = loadFile("temp.dll")
      Dim rawSymbolStore As Byte() = loadFile("temp.pdb")
      Dim myAssembly As System.Reflection.Assembly = domain.Load(rawAssembly, rawSymbolStore)
      
      Return myAssembly
   End Function 'MyResolver
   
   
   ' Creates a dynamic assembly with symbol information
   ' and saves them to temp.dll and temp.pdb
   Sub EmitAssembly(domain As AppDomain)
      Dim assemblyName As New AssemblyName()
      assemblyName.Name = "MyAssembly"
      
      Dim assemblyBuilder As AssemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save)
      Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", True)
      Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public)
      
      Dim constructorBuilder As ConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Nothing)
      Dim ilGenerator As ILGenerator = constructorBuilder.GetILGenerator()
      ilGenerator.EmitWriteLine("MyType instantiated!")
      ilGenerator.Emit(OpCodes.Ret)
      
      typeBuilder.CreateType()
      
      assemblyBuilder.Save("temp.dll")
   End Sub 'EmitAssembly

End Module 'Test

Comentarios

A partir de .NET Framework 4.NET Framework 4, el nivel de confianza de un ensamblado que se carga mediante este método es el mismo que el nivel de confianza del dominio de aplicación.Beginning with the .NET Framework 4.NET Framework 4, the trust level of an assembly that is loaded by using this method is the same as the trust level of the application domain.

Este método solo se debe usar para cargar un ensamblado en el dominio de aplicación actual.This method should be used only to load an assembly into the current application domain. Este método se proporciona por comodidad para los llamadores de interoperabilidad que no pueden Assembly.Load llamar al método estático.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Para cargar ensamblados en otros dominios de aplicación, use un método CreateInstanceAndUnwrapcomo.To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Para obtener información común a todas las sobrecargas de este método, vea la Load(AssemblyName) sobrecarga del método.For information that is common to all overloads of this method, see the Load(AssemblyName) method overload.

Seguridad

SecurityPermission
para proporcionar evidencias.to provide evidence. Enumeración asociada: ControlEvidence.Associated enumeration: ControlEvidence. Acción de seguridad Demand:.Security action: Demand.

FileIOPermission
para el acceso para leer desde un archivo o un directorio, y para tener acceso a la información de la propia ruta de acceso.for access to read from a file or directory, and for access to the information in the path itself. Enumeraciones asociadas: Read, PathDiscovery.Associated enumerations: Read, PathDiscovery.

WebPermission
para leer una ruta de acceso que no tiene el formato "File://" o\\"\\\UNC\dir" o "c\\:".for reading a path that is not in the form "file://" or "\\\UNC\dir\\" or "c:\\".

Se aplica a