AssemblyBuilder.AddResourceFile Método

Definición

Agrega un archivo de recursos existente a este ensamblado.

Sobrecargas

AddResourceFile(String, String)

Agrega un archivo de recursos existente a este ensamblado.

AddResourceFile(String, String, ResourceAttributes)

Agrega un archivo de recursos existente a este ensamblado.

AddResourceFile(String, String)

Agrega un archivo de recursos existente a este ensamblado.

public:
 void AddResourceFile(System::String ^ name, System::String ^ fileName);
public void AddResourceFile (string name, string fileName);
member this.AddResourceFile : string * string -> unit
Public Sub AddResourceFile (name As String, fileName As String)

Parámetros

name
String

Nombre lógico del recurso.

fileName
String

Nombre del archivo físico (archivo .resources) al que está asignado el nombre lógico. No debería incluir una ruta de acceso; el archivo debe estar en el mismo directorio que el ensamblado al que se agrega.

Excepciones

name se ha definido anteriormente.

o bien

Hay otro archivo en el ensamblado denominado fileName.

o bien

La longitud de name es cero.

o bien

La longitud de fileName es cero, o si fileName incluye una ruta de acceso.

name o fileName es null.

No se encuentra el archivo fileName.

El llamador no dispone del permiso requerido.

Ejemplos

En el ejemplo de código siguiente se muestra cómo adjuntar un archivo de recursos a un ensamblado creado dinámicamente mediante AddResourceFile.

using namespace System;
using namespace System::IO;
using namespace System::Threading;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
ref class AsmBuilderGetFileDemo
{
public:
   static String^ myResourceFileName = "MyResource.txt";
   static FileInfo^ CreateResourceFile()
   {
      FileInfo^ f = gcnew FileInfo( myResourceFileName );
      StreamWriter^ sw = f->CreateText();
      sw->WriteLine( "Hello, world!" );
      sw->Close();
      return f;
   }

   static AssemblyBuilder^ BuildDynAssembly()
   {
      String^ myAsmFileName = "MyAsm.dll";
      AppDomain^ myDomain = Thread::GetDomain();
      AssemblyName^ myAsmName = gcnew AssemblyName;
      myAsmName->Name = "MyDynamicAssembly";
      AssemblyBuilder^ myAsmBuilder = myDomain->DefineDynamicAssembly( myAsmName, AssemblyBuilderAccess::RunAndSave );
      myAsmBuilder->AddResourceFile( "MyResource", myResourceFileName );
      
      // To confirm that the resource file has been added to the manifest,
      // we will save the assembly as MyAsm.dll. You can view the manifest
      // and confirm the presence of the resource file by running
      // "ildasm MyAsm.dll" from the prompt in the directory where you executed
      // the compiled code.
      myAsmBuilder->Save( myAsmFileName );
      return myAsmBuilder;
   }

};

int main()
{
   FileStream^ myResourceFS = nullptr;
   AsmBuilderGetFileDemo::CreateResourceFile();
   Console::WriteLine( "The contents of MyResource.txt, via GetFile:" );
   AssemblyBuilder^ myAsm = AsmBuilderGetFileDemo::BuildDynAssembly();
   try
   {
      myResourceFS = myAsm->GetFile( AsmBuilderGetFileDemo::myResourceFileName );
   }
   catch ( NotSupportedException^ ) 
   {
      Console::WriteLine( "---" );
      Console::WriteLine( "System::Reflection::Emit::AssemblyBuilder::GetFile\nis not supported in this SDK build." );
      Console::WriteLine( "The file data will now be retrieved directly, via a new FileStream." );
      Console::WriteLine( "---" );
      myResourceFS = gcnew FileStream( AsmBuilderGetFileDemo::myResourceFileName,FileMode::Open );
   }

   StreamReader^ sr = gcnew StreamReader( myResourceFS,System::Text::Encoding::ASCII );
   Console::WriteLine( sr->ReadToEnd() );
   sr->Close();
}

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

class AsmBuilderGetFileDemo

{
   private static string myResourceFileName = "MyResource.txt";

   private static FileInfo CreateResourceFile()
   {

        FileInfo f = new FileInfo(myResourceFileName);
    StreamWriter sw = f.CreateText();

    sw.WriteLine("Hello, world!");

    sw.Close();

    return f;
   }

   private static AssemblyBuilder BuildDynAssembly()
   {

    string myAsmFileName = "MyAsm.dll";
    
    AppDomain myDomain = Thread.GetDomain();
    AssemblyName myAsmName = new AssemblyName();
    myAsmName.Name = "MyDynamicAssembly";	

    AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(
                        myAsmName,
                        AssemblyBuilderAccess.RunAndSave);

    myAsmBuilder.AddResourceFile("MyResource", myResourceFileName);

    // To confirm that the resource file has been added to the manifest,
    // we will save the assembly as MyAsm.dll. You can view the manifest
    // and confirm the presence of the resource file by running
    // "ildasm MyAsm.dll" from the prompt in the directory where you executed
    // the compiled code.

    myAsmBuilder.Save(myAsmFileName);	

    return myAsmBuilder;
   }

   public static void Main()
   {

    FileStream myResourceFS = null;

    CreateResourceFile();

    Console.WriteLine("The contents of MyResource.txt, via GetFile:");

    AssemblyBuilder myAsm = BuildDynAssembly();

    try
        {
       myResourceFS = myAsm.GetFile(myResourceFileName);
        }
    catch (NotSupportedException)
    {
       Console.WriteLine("---");
       Console.WriteLine("System.Reflection.Emit.AssemblyBuilder.GetFile\nis not supported " +
                 "in this SDK build.");
       Console.WriteLine("The file data will now be retrieved directly, via a new FileStream.");
       Console.WriteLine("---");
       myResourceFS = new FileStream(myResourceFileName,
                     FileMode.Open);
    }
    
    StreamReader sr = new StreamReader(myResourceFS, System.Text.Encoding.ASCII);
    Console.WriteLine(sr.ReadToEnd());
    sr.Close();
   }
}

Imports System.IO
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit

 _

Class AsmBuilderGetFileDemo
   
   Private Shared myResourceFileName As String = "MyResource.txt"
   
   
   Private Shared Function CreateResourceFile() As FileInfo
      
      Dim f As New FileInfo(myResourceFileName)
      Dim sw As StreamWriter = f.CreateText()
      
      sw.WriteLine("Hello, world!")
      
      sw.Close()
      
      Return f

   End Function 'CreateResourceFile
    
   
   Private Shared Function BuildDynAssembly() As AssemblyBuilder
      
      Dim myAsmFileName As String = "MyAsm.dll"
      
      Dim myDomain As AppDomain = Thread.GetDomain()
      Dim myAsmName As New AssemblyName()
      myAsmName.Name = "MyDynamicAssembly"
      
      Dim myAsmBuilder As AssemblyBuilder = myDomain.DefineDynamicAssembly(myAsmName, _
                        AssemblyBuilderAccess.RunAndSave)
      
      myAsmBuilder.AddResourceFile("MyResource", myResourceFileName)
      
      ' To confirm that the resource file has been added to the manifest,
      ' we will save the assembly as MyAsm.dll. You can view the manifest
      ' and confirm the presence of the resource file by running 
      ' "ildasm MyAsm.dll" from the prompt in the directory where you executed
      ' the compiled code. 
      myAsmBuilder.Save(myAsmFileName)
      
      Return myAsmBuilder

   End Function 'BuildDynAssembly
    
   
   Public Shared Sub Main()
      
      Dim myResourceFS As FileStream = Nothing
      
      CreateResourceFile()
      
      Console.WriteLine("The contents of MyResource.txt, via GetFile:")
      
      Dim myAsm As AssemblyBuilder = BuildDynAssembly()
      
      Try

         myResourceFS = myAsm.GetFile(myResourceFileName)

      Catch nsException As NotSupportedException
     
     Console.WriteLine("---")
     Console.WriteLine("System.Reflection.Emit.AssemblyBuilder.GetFile is not supported " + _
                 "in this SDK build.")
     Console.WriteLine("The file data will now be retrieved directly, via a new FileStream.")
     Console.WriteLine("---")
     myResourceFS = New FileStream(myResourceFileName, FileMode.Open) 

      End Try
      
      Dim sr As New StreamReader(myResourceFS, System.Text.Encoding.ASCII)
      Console.WriteLine(sr.ReadToEnd())
      sr.Close()

   End Sub

End Class

Comentarios

fileName no debe ser el mismo que el de cualquier otro módulo persistente, un recurso administrado independiente o el archivo de manifiesto independiente.

Se supone que los recursos administrados del archivo son públicos.

El archivo de recursos especificado debe estar en el directorio donde se guardará el ensamblado.

Nota

A partir de .NET Framework 2.0 Service Pack 1, este miembro ya no requiere ReflectionPermission con la ReflectionPermissionFlag.ReflectionEmit marca . (Consulte Problemas de seguridad en emisión de reflexión). Para usar esta funcionalidad, la aplicación debe tener como destino .NET Framework 3.5 o posterior.

Se aplica a

AddResourceFile(String, String, ResourceAttributes)

Agrega un archivo de recursos existente a este ensamblado.

public:
 void AddResourceFile(System::String ^ name, System::String ^ fileName, System::Reflection::ResourceAttributes attribute);
public void AddResourceFile (string name, string fileName, System.Reflection.ResourceAttributes attribute);
member this.AddResourceFile : string * string * System.Reflection.ResourceAttributes -> unit
Public Sub AddResourceFile (name As String, fileName As String, attribute As ResourceAttributes)

Parámetros

name
String

Nombre lógico del recurso.

fileName
String

Nombre del archivo físico (archivo .resources) al que está asignado el nombre lógico. No debería incluir una ruta de acceso; el archivo debe estar en el mismo directorio que el ensamblado al que se agrega.

attribute
ResourceAttributes

Atributos de recursos.

Excepciones

name se ha definido anteriormente.

o bien

Hay otro archivo en el ensamblado denominado fileName.

o bien

La longitud de name es cero o si la longitud de fileName es cero.

o bien

fileName incluye una ruta de acceso.

name o fileName es null.

Si no se encuentra el archivo fileName.

El llamador no dispone del permiso requerido.

Ejemplos

En el ejemplo de código siguiente se muestra cómo adjuntar un archivo de recursos a un ensamblado creado dinámicamente mediante AddResourceFile.

using namespace System;
using namespace System::IO;
using namespace System::Threading;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
ref class AsmBuilderGetFileDemo
{
public:
   static String^ myResourceFileName = "MyResource.txt";
   static FileInfo^ CreateResourceFile()
   {
      FileInfo^ f = gcnew FileInfo( myResourceFileName );
      StreamWriter^ sw = f->CreateText();
      sw->WriteLine( "Hello, world!" );
      sw->Close();
      return f;
   }

   static AssemblyBuilder^ BuildDynAssembly()
   {
      String^ myAsmFileName = "MyAsm.dll";
      AppDomain^ myDomain = Thread::GetDomain();
      AssemblyName^ myAsmName = gcnew AssemblyName;
      myAsmName->Name = "MyDynamicAssembly";
      AssemblyBuilder^ myAsmBuilder = myDomain->DefineDynamicAssembly( myAsmName, AssemblyBuilderAccess::RunAndSave );
      myAsmBuilder->AddResourceFile( "MyResource", myResourceFileName );
      
      // To confirm that the resource file has been added to the manifest,
      // we will save the assembly as MyAsm.dll. You can view the manifest
      // and confirm the presence of the resource file by running
      // "ildasm MyAsm.dll" from the prompt in the directory where you executed
      // the compiled code.
      myAsmBuilder->Save( myAsmFileName );
      return myAsmBuilder;
   }

};

int main()
{
   FileStream^ myResourceFS = nullptr;
   AsmBuilderGetFileDemo::CreateResourceFile();
   Console::WriteLine( "The contents of MyResource.txt, via GetFile:" );
   AssemblyBuilder^ myAsm = AsmBuilderGetFileDemo::BuildDynAssembly();
   try
   {
      myResourceFS = myAsm->GetFile( AsmBuilderGetFileDemo::myResourceFileName );
   }
   catch ( NotSupportedException^ ) 
   {
      Console::WriteLine( "---" );
      Console::WriteLine( "System::Reflection::Emit::AssemblyBuilder::GetFile\nis not supported in this SDK build." );
      Console::WriteLine( "The file data will now be retrieved directly, via a new FileStream." );
      Console::WriteLine( "---" );
      myResourceFS = gcnew FileStream( AsmBuilderGetFileDemo::myResourceFileName,FileMode::Open );
   }

   StreamReader^ sr = gcnew StreamReader( myResourceFS,System::Text::Encoding::ASCII );
   Console::WriteLine( sr->ReadToEnd() );
   sr->Close();
}

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

class AsmBuilderGetFileDemo

{
   private static string myResourceFileName = "MyResource.txt";

   private static FileInfo CreateResourceFile()
   {

        FileInfo f = new FileInfo(myResourceFileName);
    StreamWriter sw = f.CreateText();

    sw.WriteLine("Hello, world!");

    sw.Close();

    return f;
   }

   private static AssemblyBuilder BuildDynAssembly()
   {

    string myAsmFileName = "MyAsm.dll";
    
    AppDomain myDomain = Thread.GetDomain();
    AssemblyName myAsmName = new AssemblyName();
    myAsmName.Name = "MyDynamicAssembly";	

    AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(
                        myAsmName,
                        AssemblyBuilderAccess.RunAndSave);

    myAsmBuilder.AddResourceFile("MyResource", myResourceFileName);

    // To confirm that the resource file has been added to the manifest,
    // we will save the assembly as MyAsm.dll. You can view the manifest
    // and confirm the presence of the resource file by running
    // "ildasm MyAsm.dll" from the prompt in the directory where you executed
    // the compiled code.

    myAsmBuilder.Save(myAsmFileName);	

    return myAsmBuilder;
   }

   public static void Main()
   {

    FileStream myResourceFS = null;

    CreateResourceFile();

    Console.WriteLine("The contents of MyResource.txt, via GetFile:");

    AssemblyBuilder myAsm = BuildDynAssembly();

    try
        {
       myResourceFS = myAsm.GetFile(myResourceFileName);
        }
    catch (NotSupportedException)
    {
       Console.WriteLine("---");
       Console.WriteLine("System.Reflection.Emit.AssemblyBuilder.GetFile\nis not supported " +
                 "in this SDK build.");
       Console.WriteLine("The file data will now be retrieved directly, via a new FileStream.");
       Console.WriteLine("---");
       myResourceFS = new FileStream(myResourceFileName,
                     FileMode.Open);
    }
    
    StreamReader sr = new StreamReader(myResourceFS, System.Text.Encoding.ASCII);
    Console.WriteLine(sr.ReadToEnd());
    sr.Close();
   }
}

Imports System.IO
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit

 _

Class AsmBuilderGetFileDemo
   
   Private Shared myResourceFileName As String = "MyResource.txt"
   
   
   Private Shared Function CreateResourceFile() As FileInfo
      
      Dim f As New FileInfo(myResourceFileName)
      Dim sw As StreamWriter = f.CreateText()
      
      sw.WriteLine("Hello, world!")
      
      sw.Close()
      
      Return f

   End Function 'CreateResourceFile
    
   
   Private Shared Function BuildDynAssembly() As AssemblyBuilder
      
      Dim myAsmFileName As String = "MyAsm.dll"
      
      Dim myDomain As AppDomain = Thread.GetDomain()
      Dim myAsmName As New AssemblyName()
      myAsmName.Name = "MyDynamicAssembly"
      
      Dim myAsmBuilder As AssemblyBuilder = myDomain.DefineDynamicAssembly(myAsmName, _
                        AssemblyBuilderAccess.RunAndSave)
      
      myAsmBuilder.AddResourceFile("MyResource", myResourceFileName)
      
      ' To confirm that the resource file has been added to the manifest,
      ' we will save the assembly as MyAsm.dll. You can view the manifest
      ' and confirm the presence of the resource file by running 
      ' "ildasm MyAsm.dll" from the prompt in the directory where you executed
      ' the compiled code. 
      myAsmBuilder.Save(myAsmFileName)
      
      Return myAsmBuilder

   End Function 'BuildDynAssembly
    
   
   Public Shared Sub Main()
      
      Dim myResourceFS As FileStream = Nothing
      
      CreateResourceFile()
      
      Console.WriteLine("The contents of MyResource.txt, via GetFile:")
      
      Dim myAsm As AssemblyBuilder = BuildDynAssembly()
      
      Try

         myResourceFS = myAsm.GetFile(myResourceFileName)

      Catch nsException As NotSupportedException
     
     Console.WriteLine("---")
     Console.WriteLine("System.Reflection.Emit.AssemblyBuilder.GetFile is not supported " + _
                 "in this SDK build.")
     Console.WriteLine("The file data will now be retrieved directly, via a new FileStream.")
     Console.WriteLine("---")
     myResourceFS = New FileStream(myResourceFileName, FileMode.Open) 

      End Try
      
      Dim sr As New StreamReader(myResourceFS, System.Text.Encoding.ASCII)
      Console.WriteLine(sr.ReadToEnd())
      sr.Close()

   End Sub

End Class

Comentarios

fileName no debe ser el mismo que el de cualquier otro módulo persistente, un recurso administrado independiente o el archivo de manifiesto independiente.

Los atributos se pueden especificar para el recurso administrado.

El archivo de recursos especificado debe estar en el directorio donde se guardará el ensamblado.

Nota

A partir de .NET Framework 2.0 Service Pack 1, este miembro ya no requiere ReflectionPermission con la ReflectionPermissionFlag.ReflectionEmit marca . (Consulte Problemas de seguridad en emisión de reflexión). Para usar esta funcionalidad, la aplicación debe tener como destino .NET Framework 3.5 o posterior.

Se aplica a