AssemblyBuilder.DefineResource AssemblyBuilder.DefineResource AssemblyBuilder.DefineResource AssemblyBuilder.DefineResource Method

Definición

Define un recurso administrado independiente para este ensamblado.Defines a standalone managed resource for this assembly.

Sobrecargas

DefineResource(String, String, String) DefineResource(String, String, String) DefineResource(String, String, String) DefineResource(String, String, String)

Define un recurso administrado independiente para este ensamblado con el atributo de recurso público predeterminado.Defines a standalone managed resource for this assembly with the default public resource attribute.

DefineResource(String, String, String, ResourceAttributes) DefineResource(String, String, String, ResourceAttributes) DefineResource(String, String, String, ResourceAttributes) DefineResource(String, String, String, ResourceAttributes)

Define un recurso administrado independiente para este ensamblado.Defines a standalone managed resource for this assembly. Se pueden especificar atributos para el recurso administrado.Attributes can be specified for the managed resource.

DefineResource(String, String, String) DefineResource(String, String, String) DefineResource(String, String, String) DefineResource(String, String, String)

Define un recurso administrado independiente para este ensamblado con el atributo de recurso público predeterminado.Defines a standalone managed resource for this assembly with the default public resource attribute.

public:
 System::Resources::IResourceWriter ^ DefineResource(System::String ^ name, System::String ^ description, System::String ^ fileName);
public System.Resources.IResourceWriter DefineResource (string name, string description, string fileName);
member this.DefineResource : string * string * string -> System.Resources.IResourceWriter
Public Function DefineResource (name As String, description As String, fileName As String) As IResourceWriter

Parámetros

name
String String String String

Nombre lógico del recurso.The logical name of the resource.

description
String String String String

Descripción textual del recurso.A textual description of the resource.

fileName
String String String String

Nombre de archivo físico (archivo .resources) al que se asigna el nombre lógico.The physical file name (.resources file) to which the logical name is mapped. No debe incluir una ruta de acceso.This should not include a path.

Devoluciones

Objeto ResourceWriter del recurso especificado.A ResourceWriter object for the specified resource.

Excepciones

Se ha definido previamente name.name has been previously defined.

O bien-or- Hay otro archivo en el ensamblado denominado fileName.There is another file in the assembly named fileName.

O bien-or- La longitud de name es cero.The length of name is zero.

O bien-or- La longitud de fileName es cero.The length of fileName is zero.

O bien-or- fileName incluye una ruta de acceso.fileName includes a path.

El llamador no dispone del permiso requerido.The caller does not have the required permission.

Ejemplos

En el ejemplo siguiente se usa el DefineResource método para obtener un escritor de recursos.The following example uses the DefineResource method to get a resource writer. El ejemplo utiliza el sistema de escritura de recursos para agregar tres cadenas de recursos.The example uses the resource writer to add three resource strings.

using namespace System;
using namespace System::Threading;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
using namespace System::Resources;

/*
   The following program demonstrates the 'DefineResource' and 'DefineVersionInfoResource' 
   methods of 'AssemblyBuilder' class. It builds an assembly and a resource file at runtime.
   The unmanaged version information like product, product version, Company, Copyright, 
   trademark are defined with 'DefineVersionInfoResource' method.
*/
static Type^ CreateAssembly( AppDomain^ appDomain );

int main()
{
   AssemblyBuilder^ myAssembly;
   IResourceWriter^ myResourceWriter;
   myAssembly = safe_cast<AssemblyBuilder^>(CreateAssembly( Thread::GetDomain() )->Assembly);
   myResourceWriter = myAssembly->DefineResource( "myResourceFile", "A sample Resource File", "MyEmitAssembly.MyResource.resources" );
   myResourceWriter->AddResource( "AddResource 1", "First added resource" );
   myResourceWriter->AddResource( "AddResource 2", "Second added resource" );
   myResourceWriter->AddResource( "AddResource 3", "Third added resource" );
   myAssembly->DefineVersionInfoResource( "AssemblySample",  "2:0:0:1", "Microsoft Corporation", "@Copyright Microsoft Corp. 1990-2001", ".NET is a trademark of Microsoft Corporation" );
   myAssembly->Save( "MyEmitAssembly.dll" );
}

// Create the callee transient dynamic assembly.
static Type^ CreateAssembly( AppDomain^ appDomain )
{
   AssemblyName^ myAssemblyName = gcnew AssemblyName;
   myAssemblyName->Name = "MyEmitAssembly";
   AssemblyBuilder^ myAssembly = appDomain->DefineDynamicAssembly( myAssemblyName, AssemblyBuilderAccess::Save );
   ModuleBuilder^ myModule = myAssembly->DefineDynamicModule( "EmittedModule", "EmittedModule.mod" );

   // Define a public class named "HelloWorld" in the assembly.
   TypeBuilder^ helloWorldClass = myModule->DefineType( "HelloWorld", TypeAttributes::Public );

   // Define the Display method.
   MethodBuilder^ myMethod = helloWorldClass->DefineMethod( "Display", MethodAttributes::Public, String::typeid, nullptr );

   // Generate IL for GetGreeting.
   ILGenerator^ methodIL = myMethod->GetILGenerator();
   methodIL->Emit( OpCodes::Ldstr, "Display method get called." );
   methodIL->Emit( OpCodes::Ret );

   // Returns the type HelloWorld.
   return (helloWorldClass->CreateType());
}
public static void Main() 
{
   AssemblyBuilder myAssembly;
   IResourceWriter myResourceWriter; 
   myAssembly = (AssemblyBuilder)CreateAssembly(Thread.GetDomain()).Assembly;
      
   myResourceWriter = myAssembly.DefineResource("myResourceFile",
      "A sample Resource File", "MyEmitAssembly.MyResource.resources");
   myResourceWriter.AddResource("AddResource 1", "First added resource");
   myResourceWriter.AddResource("AddResource 2", "Second added resource");
   myResourceWriter.AddResource("AddResource 3", "Third added resource");

   myAssembly.DefineVersionInfoResource("AssemblySample", "2:0:0:1",
      "Microsoft Corporation", "@Copyright Microsoft Corp. 1990-2001",
      ".NET is a trademark of Microsoft Corporation");
   myAssembly.Save("MyEmitAssembly.dll");
}

// Create the callee transient dynamic assembly.
private static Type CreateAssembly(AppDomain appDomain) 
{
   AssemblyName myAssemblyName = new AssemblyName();
   myAssemblyName.Name = "MyEmitAssembly";
   AssemblyBuilder myAssembly = appDomain.DefineDynamicAssembly(myAssemblyName, 
      AssemblyBuilderAccess.Save);
   ModuleBuilder myModule = myAssembly.DefineDynamicModule("EmittedModule",
      "EmittedModule.mod");

   // Define a public class named "HelloWorld" in the assembly.
   TypeBuilder helloWorldClass = 
      myModule.DefineType("HelloWorld", TypeAttributes.Public);
   // Define the Display method.
   MethodBuilder myMethod = helloWorldClass.DefineMethod("Display", 
      MethodAttributes.Public, typeof(String), null);

   // Generate IL for GetGreeting.
   ILGenerator methodIL = myMethod.GetILGenerator();
   methodIL.Emit(OpCodes.Ldstr, "Display method get called.");
   methodIL.Emit(OpCodes.Ret);

   // Returns the type HelloWorld.
   return(helloWorldClass.CreateType());
}   
Public Shared Sub Main()
   Dim myAssembly As AssemblyBuilder
   Dim myResourceWriter As IResourceWriter
   myAssembly = CType(CreateAssembly(Thread.GetDomain()).Assembly, AssemblyBuilder)
   
   myResourceWriter = myAssembly.DefineResource("myResourceFile", "A sample Resource File", _
                                                      "MyEmitAssembly.MyResource.resources")
   myResourceWriter.AddResource("AddResource 1", "First added resource")
   myResourceWriter.AddResource("AddResource 2", "Second added resource")
   myResourceWriter.AddResource("AddResource 3", "Third added resource")
   
   myAssembly.DefineVersionInfoResource("AssemblySample", "2:0:0:1", "Microsoft Corporation", _
         "@Copyright Microsoft Corp. 1990-2001", ".NET is a trademark of Microsoft Corporation")
   myAssembly.Save("MyEmitAssembly.dll")
End Sub 'Main

' Create the callee transient dynamic assembly.
Private Shared Function CreateAssembly(myAppDomain As AppDomain) As Type
   Dim myAssemblyName As New AssemblyName()
   myAssemblyName.Name = "MyEmitAssembly"
   Dim myAssembly As AssemblyBuilder = myAppDomain.DefineDynamicAssembly(myAssemblyName, _
                                                            AssemblyBuilderAccess.Save)
   Dim myModule As ModuleBuilder = myAssembly.DefineDynamicModule("EmittedModule", _
                                                            "EmittedModule.mod")
   
   ' Define a public class named "HelloWorld" in the assembly.
   Dim helloWorldClass As TypeBuilder = myModule.DefineType("HelloWorld", TypeAttributes.Public)
   ' Define the Display method.
   Dim myMethod As MethodBuilder = helloWorldClass.DefineMethod("Display", _
                                 MethodAttributes.Public, GetType(String), Nothing)
   
   ' Generate IL for GetGreeting.
   Dim methodIL As ILGenerator = myMethod.GetILGenerator()
   methodIL.Emit(OpCodes.Ldstr, "Display method get called.")
   methodIL.Emit(OpCodes.Ret)
   ' Returns the type HelloWorld.
   Return helloWorldClass.CreateType()
End Function 'CreateAssembly

Comentarios

Se pueden agregar recursos muy específicos con el valor devuelto ResourceWriter mediante una llamada a AddResource.Fine grain resources can be added with the returned ResourceWriter by calling AddResource.

fileName no se debe ser el mismo que el de cualquier otro módulo con persistencia, recurso administrado independiente o el archivo de manifiesto independiente.fileName should not be the same as that of any other persistable module, stand-alone managed resource, or the stand-alone manifest file.

El runtime llama a la Close método cuando se guarda el ensamblado dinámico.The runtime calls the Close method when the dynamic assembly is saved.

Nota

A partir de la .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, ya no requiere este miembro ReflectionPermission con el ReflectionPermissionFlag.ReflectionEmit marca.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this member no longer requires ReflectionPermission with the ReflectionPermissionFlag.ReflectionEmit flag. (Consulte problemas de seguridad en Reflection emiten.) Para utilizar esta funcionalidad, la aplicación debe utilizar .NET Framework 3,5.NET Framework 3.5 o posterior como destino.(See Security Issues in Reflection Emit.) To use this functionality, your application should target the .NET Framework 3,5.NET Framework 3.5 or later.

Seguridad

ReflectionPermission
Cuando se invoca en tiempo de ejecución a través de mecanismos como InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]).when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumeración asociada: MemberAccess.Associated enumeration: MemberAccess.

FileIOPermission
Escribir = true o Append = trueWrite=true or Append=true

DefineResource(String, String, String, ResourceAttributes) DefineResource(String, String, String, ResourceAttributes) DefineResource(String, String, String, ResourceAttributes) DefineResource(String, String, String, ResourceAttributes)

Define un recurso administrado independiente para este ensamblado.Defines a standalone managed resource for this assembly. Se pueden especificar atributos para el recurso administrado.Attributes can be specified for the managed resource.

public:
 System::Resources::IResourceWriter ^ DefineResource(System::String ^ name, System::String ^ description, System::String ^ fileName, System::Reflection::ResourceAttributes attribute);
public System.Resources.IResourceWriter DefineResource (string name, string description, string fileName, System.Reflection.ResourceAttributes attribute);
member this.DefineResource : string * string * string * System.Reflection.ResourceAttributes -> System.Resources.IResourceWriter
Public Function DefineResource (name As String, description As String, fileName As String, attribute As ResourceAttributes) As IResourceWriter

Parámetros

name
String String String String

Nombre lógico del recurso.The logical name of the resource.

description
String String String String

Descripción textual del recurso.A textual description of the resource.

fileName
String String String String

Nombre de archivo físico (archivo .resources) al que se asigna el nombre lógico.The physical file name (.resources file) to which the logical name is mapped. No debe incluir una ruta de acceso.This should not include a path.

attribute
ResourceAttributes ResourceAttributes ResourceAttributes ResourceAttributes

Atributos de recursos.The resource attributes.

Devoluciones

Objeto ResourceWriter del recurso especificado.A ResourceWriter object for the specified resource.

Excepciones

name se ha definido previamente o hay otro archivo en el ensamblado denominado fileName.name has been previously defined or if there is another file in the assembly named fileName.

O bien-or- La longitud de name es cero.The length of name is zero.

O bien-or- La longitud de fileName es cero.The length of fileName is zero.

O bien-or- fileName incluye una ruta de acceso.fileName includes a path.

El llamador no dispone del permiso requerido.The caller does not have the required permission.

Comentarios

Se pueden agregar recursos concretos con el valor devuelto ResourceWriter mediante una llamada a AddResource.Fine-grain resources can be added with the returned ResourceWriter by calling AddResource.

fileName no se debe ser el mismo que el de cualquier otro módulo con persistencia, recurso administrado independiente o el archivo de manifiesto independiente.fileName should not be the same as that of any other persistable module, standalone managed resource, or the standalone manifest file.

El runtime llama a la Close método cuando se guarda el ensamblado dinámico.The runtime calls the Close method when the dynamic assembly is saved.

Nota

A partir de la .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, ya no requiere este miembro ReflectionPermission con el ReflectionPermissionFlag.ReflectionEmit marca.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this member no longer requires ReflectionPermission with the ReflectionPermissionFlag.ReflectionEmit flag. (Consulte problemas de seguridad en Reflection emiten.) Para utilizar esta funcionalidad, la aplicación debe utilizar .NET Framework 3,5.NET Framework 3.5 o posterior como destino.(See Security Issues in Reflection Emit.) To use this functionality, your application should target the .NET Framework 3,5.NET Framework 3.5 or later.

Seguridad

ReflectionPermission
Cuando se invoca en tiempo de ejecución a través de mecanismos como InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]).when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumeración asociada: MemberAccess.Associated enumeration: MemberAccess.

FileIOPermission
Escribir = true o Append = trueWrite=true or Append=true

Se aplica a