AssemblyBuilder.DefineUnmanagedResource Метод

Определение

Определяет неуправляемый ресурс для данной сборки.Defines an unmanaged resource for this assembly.

Перегрузки

DefineUnmanagedResource(String)

Определяет файл неуправляемого ресурса для данной сборки по заданному имени файла ресурсов.Defines an unmanaged resource file for this assembly given the name of the resource file.

DefineUnmanagedResource(Byte[])

Определяет неуправляемый ресурс для данной сборки как непрозрачный BLOB-объект байтов.Defines an unmanaged resource for this assembly as an opaque blob of bytes.

DefineUnmanagedResource(String)

Определяет файл неуправляемого ресурса для данной сборки по заданному имени файла ресурсов.Defines an unmanaged resource file for this assembly given the name of the resource file.

public:
 void DefineUnmanagedResource(System::String ^ resourceFileName);
public void DefineUnmanagedResource (string resourceFileName);
member this.DefineUnmanagedResource : string -> unit
Public Sub DefineUnmanagedResource (resourceFileName As String)

Параметры

resourceFileName
String

Имя файла ресурсов.The name of the resource file.

Исключения

Неуправляемый ресурс был определен ранее.An unmanaged resource was previously defined.

-или--or- Файл resourceFileName нечитаем.The file resourceFileName is not readable.

-или--or- resourceFileName является пустой строкой ("").resourceFileName is the empty string ("").

resourceFileName имеет значение null.resourceFileName is null.

resourceFileName не найден.resourceFileName is not found.

-или--or- resourceFileName является каталогом.resourceFileName is a directory.

У вызывающего объекта отсутствует необходимое разрешение.The caller does not have the required permission.

Примеры

В приведенном ниже примере показан вызов с DefineUnmanagedResource передачей внешнего файла ресурсов.The example below demonstrates a call to DefineUnmanagedResource, passing an external resource file.

void main()
{
   AssemblyBuilder^ myAssembly = CreateAssembly("MyEmitTestAssembly");
   
   // Defines a standalone managed resource for this assembly.
   IResourceWriter^ myResourceWriter = 
      myAssembly->DefineResource( "myResourceFile", "A sample Resource File", 
         "MyAssemblyResource.resources", ResourceAttributes::Private );

   myResourceWriter->AddResource( "AddResource Test", "Testing for the added resource" );

   myAssembly->Save(myAssembly->GetName()->Name + ".dll" );
   
   // Defines an unmanaged resource file for this assembly.
   myAssembly->DefineUnmanagedResource(  "MyAssemblyResource.resources" );
};

   internal static void Main()
   {
      AssemblyBuilder myAssembly = CreateAssembly("MyEmitTestAssembly");

      // Defines a standalone managed resource for this assembly.
      IResourceWriter myResourceWriter = myAssembly.DefineResource("myResourceFile",
         "A sample Resource File", "MyAssemblyResource.resources",
         ResourceAttributes.Private);

      myResourceWriter.AddResource("AddResource Test", "Testing for the added resource");

      myAssembly.Save(myAssembly.GetName().Name + ".dll");

      // Defines an unmanaged resource file for this assembly.
      myAssembly.DefineUnmanagedResource("MyAssemblyResource.resources");
   }

   private static AssemblyBuilder CreateAssembly(string name)
   {
      AssemblyName aName = new AssemblyName(name);
      AssemblyBuilder myAssembly =
         AppDomain.CurrentDomain.DefineDynamicAssembly(aName,
            AssemblyBuilderAccess.Save);

      // Define a dynamic module.
      ModuleBuilder myModule =
         myAssembly.DefineDynamicModule(aName.Name, aName.Name + ".dll");

      // Define a public class named "EmitClass" in the assembly.
      TypeBuilder myEmitClass = myModule.DefineType("EmitClass", TypeAttributes.Public);

      // Define the Display method.
      MethodBuilder myMethod = myEmitClass.DefineMethod("Display",
         MethodAttributes.Public, typeof(String), null);

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

      myEmitClass.CreateType();

      return(myAssembly);
   }
}
Friend Shared Sub Main()
   Dim myAssembly As AssemblyBuilder = _
       CreateAssembly("MyEmitTestAssembly")
   
   ' Defines a standalone managed resource for this assembly.
   Dim myResourceWriter As IResourceWriter = _
      myAssembly.DefineResource("myResourceFile", _
         "A sample Resource File", "MyAssemblyResource.resources", _
         ResourceAttributes.Private)

   myResourceWriter.AddResource("AddResource Test", "Testing for the added resource")

   myAssembly.Save(myAssembly.GetName().Name & ".dll")
   
   ' Defines an unmanaged resource file for this assembly.
   myAssembly.DefineUnmanagedResource("MyAssemblyResource.resources")

End Sub 

Private Shared Function CreateAssembly(ByVal name As String) As AssemblyBuilder

   Dim aName As New AssemblyName(name)

   Dim myAssembly As AssemblyBuilder = _
      AppDomain.CurrentDomain.DefineDynamicAssembly(aName, _
         AssemblyBuilderAccess.Save)
   
   ' Define a dynamic module.
   Dim myModule As ModuleBuilder = _
      myAssembly.DefineDynamicModule(aName.Name, aName.Name & ".dll")

   ' Define a public class named "EmitClass" in the assembly.
   Dim myEmitClass As TypeBuilder = _
      myModule.DefineType("EmitClass", TypeAttributes.Public)
   
   ' Define the Display method.
   Dim myMethod As MethodBuilder = _
      myEmitClass.DefineMethod("Display", MethodAttributes.Public, _
                                             GetType(String), Nothing)
   
   ' Generate IL for Display method.
   Dim methodIL As ILGenerator = myMethod.GetILGenerator()
   methodIL.Emit(OpCodes.Ldstr, "Display method get called.")
   methodIL.Emit(OpCodes.Ret)
   
   myEmitClass.CreateType()

   Return myAssembly

End Function 

Комментарии

Сборка может быть связана только с одним неуправляемым ресурсом.An assembly can be associated with only one unmanaged resource. Это означает, что вызов метода DefineVersionInfoResource или DefineUnmanagedResource после того, как один из методов был вызван ранее, вызовет исключение System. ArgumentException.This means that calling DefineVersionInfoResource or DefineUnmanagedResource after either one of the methods was called previously will throw the System.ArgumentException. Несколько неуправляемых ресурсов необходимо объединить с помощью такого средства, как Microsoft Ресмерже Utility (не представленного в среде CLR).Multiple unmanaged resources need to be merged with a tool such as the Microsoft ResMerge utility (not supplied with the common language runtime).

Примечание

Начиная с .NET Framework 2.0 с пакетом обновления 1 (SP1).NET Framework 2.0 Service Pack 1 , этот член больше не требует наличия ReflectionPermission ReflectionPermissionFlag.ReflectionEmit флага.Starting with the .NET Framework 2.0 с пакетом обновления 1 (SP1).NET Framework 2.0 Service Pack 1, this member no longer requires ReflectionPermission with the ReflectionPermissionFlag.ReflectionEmit flag. (См. раздел вопросы безопасности в порождении отражения.) Чтобы использовать эту функцию, приложение должно быть предназначено для .NET Framework 3,5.NET Framework 3.5 или более поздней версии.(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.

Применяется к

DefineUnmanagedResource(Byte[])

Определяет неуправляемый ресурс для данной сборки как непрозрачный BLOB-объект байтов.Defines an unmanaged resource for this assembly as an opaque blob of bytes.

public:
 void DefineUnmanagedResource(cli::array <System::Byte> ^ resource);
public void DefineUnmanagedResource (byte[] resource);
member this.DefineUnmanagedResource : byte[] -> unit
Public Sub DefineUnmanagedResource (resource As Byte())

Параметры

resource
Byte[]

Непрозрачный BLOB-объект байтов, представляющий неуправляемый ресурс.The opaque blob of bytes representing the unmanaged resource.

Исключения

Неуправляемый ресурс был определен ранее.An unmanaged resource was previously defined.

resource имеет значение null.resource is null.

У вызывающего объекта отсутствует необходимое разрешение.The caller does not have the required permission.

Примеры

В следующем примере кода создается и присоединяется массив байтов, представляющий неуправляемый ресурс, в динамическую сборку с помощью DefineUnmanagedResource .The following code sample creates and attaches an array of bytes representing an unmanaged resource to a dynamic assembly, using DefineUnmanagedResource.

/*
   The following program demonstrates the 'DefineResource' and 'DefineUnmanagedResource'
   methods of 'AssemblyBuilder' class. It builds an assembly and a resource file at runtime.
   An unmanaged resource file is also defined for the same resource file. The EmittedTest2.cpp file
   calls the methods of "MyEmitAssembly.dll" assembly and the message is displayed to console.
*/
using namespace System;
using namespace System::Threading;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
using namespace System::Resources;

   static AssemblyBuilder^ CreateAssembly( String^ name )
   {
      AssemblyName^ aName = gcnew AssemblyName(name);
      AssemblyBuilder^ myAssembly = 
         AppDomain::CurrentDomain->DefineDynamicAssembly( aName, 
            AssemblyBuilderAccess::Save );
      
      // Define a dynamic module.
      ModuleBuilder^ myModule = 
         myAssembly->DefineDynamicModule( aName->Name, aName->Name + ".dll" );
      
      // Define a public class named "EmitClass" in the assembly.
      TypeBuilder^ myEmitClass = 
         myModule->DefineType( "EmitClass", TypeAttributes::Public );
      
      // Define the Display method.
      MethodBuilder^ myMethod = 
         myEmitClass->DefineMethod( "Display", MethodAttributes::Public, 
            String::typeid, nullptr );
      
      // Generate IL for Display method.
      ILGenerator^ methodIL = myMethod->GetILGenerator();
      methodIL->Emit( OpCodes::Ldstr, "Display method gets called." );
      methodIL->Emit( OpCodes::Ret );
      
      myEmitClass->CreateType();

      return (myAssembly);
   };

   void main()
   {
      AssemblyBuilder^ myAssembly = CreateAssembly("MyEmitTestAssembly");
      
      // Defines a standalone managed resource for this assembly.
      IResourceWriter^ myResourceWriter = 
         myAssembly->DefineResource( "myResourceFile", "A sample Resource File", 
            "MyAssemblyResource.resources", ResourceAttributes::Private );

      myResourceWriter->AddResource( "AddResource Test", "Testing for the added resource" );

      myAssembly->Save(myAssembly->GetName()->Name + ".dll" );
      
      // Defines an unmanaged resource file for this assembly.
      myAssembly->DefineUnmanagedResource( gcnew array<Byte>{01, 00, 01} );
   };

using System;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;

public class MyAssemblyResource
{
   internal static void Main()
   {
      AssemblyBuilder myAssembly = CreateAssembly("MyEmitTestAssembly");

      // Defines a standalone managed resource for this assembly.
      IResourceWriter myResourceWriter = myAssembly.DefineResource("myResourceFile",
         "A sample Resource File", "MyAssemblyResource.resources",
         ResourceAttributes.Private);

      myResourceWriter.AddResource("AddResource Test", "Testing for the added resource");

      myAssembly.Save(myAssembly.GetName().Name + ".dll");

      // Defines an unmanaged resource file for this assembly.
      myAssembly.DefineUnmanagedResource(new byte[]{01, 00, 01});
   }

   private static AssemblyBuilder CreateAssembly(string name)
   {
      AssemblyName aName = new AssemblyName(name);
      AssemblyBuilder myAssembly =
         AppDomain.CurrentDomain.DefineDynamicAssembly(aName,
            AssemblyBuilderAccess.Save);

      // Define a dynamic module.
      ModuleBuilder myModule =
         myAssembly.DefineDynamicModule(aName.Name, aName.Name + ".dll");

      // Define a public class named "EmitClass" in the assembly.
      TypeBuilder myEmitClass = myModule.DefineType("EmitClass", TypeAttributes.Public);

      // Define the Display method.
      MethodBuilder myMethod = myEmitClass.DefineMethod("Display",
         MethodAttributes.Public, typeof(String), null);

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

      myEmitClass.CreateType();

      return(myAssembly);
   }
}
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Resources

Public Class MyAssemblyResource
   
   Friend Shared Sub Main()
      Dim myAssembly As AssemblyBuilder = _
          CreateAssembly("MyEmitTestAssembly")
      
      ' Defines a standalone managed resource for this assembly.
      Dim myResourceWriter As IResourceWriter = _
         myAssembly.DefineResource("myResourceFile", _
            "A sample Resource File", "MyAssemblyResource.resources", _
            ResourceAttributes.Private)

      myResourceWriter.AddResource("AddResource Test", "Testing for the added resource")

      myAssembly.Save(myAssembly.GetName().Name & ".dll")
      
      ' Defines an unmanaged resource file for this assembly.
      myAssembly.DefineUnmanagedResource(New Byte() {1, 0, 1})

   End Sub 
   
   Private Shared Function CreateAssembly(ByVal name As String) As AssemblyBuilder

      Dim aName As New AssemblyName(name)

      Dim myAssembly As AssemblyBuilder = _
         AppDomain.CurrentDomain.DefineDynamicAssembly(aName, _
            AssemblyBuilderAccess.Save)
      
      ' Define a dynamic module.
      Dim myModule As ModuleBuilder = _
         myAssembly.DefineDynamicModule(aName.Name, aName.Name & ".dll")

      ' Define a public class named "EmitClass" in the assembly.
      Dim myEmitClass As TypeBuilder = _
         myModule.DefineType("EmitClass", TypeAttributes.Public)
      
      ' Define the Display method.
      Dim myMethod As MethodBuilder = _
         myEmitClass.DefineMethod("Display", MethodAttributes.Public, _
                                                GetType(String), Nothing)
      
      ' Generate IL for Display method.
      Dim methodIL As ILGenerator = myMethod.GetILGenerator()
      methodIL.Emit(OpCodes.Ldstr, "Display method get called.")
      methodIL.Emit(OpCodes.Ret)
      
      myEmitClass.CreateType()

      Return myAssembly

   End Function 
End Class 

Комментарии

Сборка может быть связана только с одним неуправляемым ресурсом.An assembly can be associated with only one unmanaged resource. Это означает, что вызов метода DefineVersionInfoResource или DefineUnmanagedResource после того, как один из методов был вызван ранее, вызовет исключение System. ArgumentException.This means that calling DefineVersionInfoResource or DefineUnmanagedResource after either one of the methods was called previously will throw the System.ArgumentException being throw. Несколько неуправляемых ресурсов необходимо объединить с помощью такого средства, как Microsoft Ресмерже Utility (не представленного в среде CLR).Multiple unmanaged resources need to be merged with a tool such as the Microsoft ResMerge utility (not supplied with the common language runtime).

Применяется к