Procedimiento para determinar si un archivo es un ensamblado

Un archivo es un ensamblado únicamente si está administrado y contiene una entrada de ensamblado en sus metadatos. Para más información sobre ensamblados y metadatos, vea Manifiesto del ensamblado.

Cómo determinar manualmente si un archivo es un ensamblado

  1. Inicie la herramienta Ildasm.exe (Desensamblador de IL).

  2. Cargue el archivo que quiere probar.

  3. Si ILDASM notifica que el archivo no es un archivo ejecutable portable (PE), entonces no es un ensamblado. Para obtener más información, vea el tema Cómo: Ver el contenido de un ensamblado.

Cómo determinar mediante programación si un archivo es un ensamblado

Uso de la clase AssemblyName

  1. Llame al método AssemblyName.GetAssemblyName; para ello, pase el nombre y la ruta de acceso de archivo completa del archivo que está probando.

  2. Si se genera una excepción BadImageFormatException, el archivo no es un ensamblado.

En este ejemplo se prueba un archivo DLL para ver si es un ensamblado.

using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;

static class ExampleAssemblyName
{
    public static void CheckAssembly()
    {
        try
        {
            string path = Path.Combine(
                RuntimeEnvironment.GetRuntimeDirectory(),
                "System.Net.dll");

            AssemblyName testAssembly = AssemblyName.GetAssemblyName(path);
            Console.WriteLine("Yes, the file is an assembly.");
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("The file cannot be found.");
        }
        catch (BadImageFormatException)
        {
            Console.WriteLine("The file is not an assembly.");
        }
        catch (FileLoadException)
        {
            Console.WriteLine("The assembly has already been loaded.");
        }
    }

    /* Output: 
    Yes, the file is an assembly.  
    */
}
Imports System
Imports System.IO
Imports System.Reflection
Imports System.Runtime.InteropServices

Module ExampleAssemblyName
    Sub CheckAssembly()
        Try
            Dim filePath As String = Path.Combine(
                RuntimeEnvironment.GetRuntimeDirectory(),
                "System.Net.dll")

            Dim testAssembly As AssemblyName =
                                AssemblyName.GetAssemblyName(filePath)
            Console.WriteLine("Yes, the file is an Assembly.")
        Catch ex As FileNotFoundException
            Console.WriteLine("The file cannot be found.")
        Catch ex As BadImageFormatException
            Console.WriteLine("The file is not an Assembly.")
        Catch ex As FileLoadException
            Console.WriteLine("The Assembly has already been loaded.")
        End Try
    End Sub
End Module
' Output:  
' Yes, the file is an Assembly.  

El método GetAssemblyName carga el archivo de prueba y, después, lo libera cuando se lee la información.

Uso de la clase PEReader

  1. Si tiene como destino .NET Standard o .NET Framework, instale el paquete NuGet System.Reflection.Metadata. (Al tener como destino .NET Core o .NET 5+, este paso no es necesario porque esta biblioteca se incluye en el marco compartido).

  2. Cree una instancia de System.IO.FileStream para leer datos del archivo que está probando.

  3. Cree una instancia de System.Reflection.PortableExecutable.PEReader y pase la secuencia de archivos al constructor.

  4. Comprobar el valor de la propiedad HasMetadata. Si el valor es false, el archivo no es un ensamblado.

  5. Llame al método GetMetadataReader en la instancia del lector de PE para crear un lector de metadatos.

  6. Comprobar el valor de la propiedad IsAssembly. Si el valor es true, el archivo no es un ensamblado.

A diferencia del método GetAssemblyName, la clase PEReader no inicia una excepción en archivos portable ejecutables (PE) nativos. Esto le permite evitar el costo de rendimiento adicional causado por excepciones cuando necesite comprobar dichos archivos. Todavía necesita controlar excepciones en caso de que el archivo no exista o no sea un archivo PE.

En este ejemplo se muestra cómo determinar si un archivo es un ensamblado mediante la clase PEReader.

using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Runtime.InteropServices;

static class ExamplePeReader
{
    static bool IsAssembly(string path)
    {
        using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

        // Try to read CLI metadata from the PE file.
        using var peReader = new PEReader(fs);

        if (!peReader.HasMetadata)
        {
            return false; // File does not have CLI metadata.
        }

        // Check that file has an assembly manifest.
        MetadataReader reader = peReader.GetMetadataReader();
        return reader.IsAssembly;
    }

    public static void CheckAssembly()
    {
        string path = Path.Combine(
                RuntimeEnvironment.GetRuntimeDirectory(),
                "System.Net.dll");

        try
        {
            if (IsAssembly(path))
            {
                Console.WriteLine("Yes, the file is an assembly.");
            }
            else
            {
                Console.WriteLine("The file is not an assembly.");
            }
        }
        catch (BadImageFormatException)
        {
            Console.WriteLine("The file is not an executable.");
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("The file cannot be found.");
        }
    }

    /* Output: 
    Yes, the file is an assembly.  
    */
}
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Reflection.Metadata
Imports System.Reflection.PortableExecutable
Imports System.Runtime.InteropServices

Module ExamplePeReader
    Function IsAssembly(path As String) As Boolean

        Dim fs As FileStream = New FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)

        ' Try to read CLI metadata from the PE file.
        Dim peReader As PEReader = New PEReader(fs)
        Using (peReader)
            If Not peReader.HasMetadata Then
                Return False ' File does Not have CLI metadata.
            End If

            ' Check that file has an assembly manifest.
            Dim reader As MetadataReader = peReader.GetMetadataReader()
            Return reader.IsAssembly
        End Using
    End Function

    Sub CheckAssembly()
        Dim filePath As String = Path.Combine(
                RuntimeEnvironment.GetRuntimeDirectory(),
                "System.Net.dll")

        Try
            If IsAssembly(filePath) Then
                Console.WriteLine("Yes, the file is an assembly.")
            Else
                Console.WriteLine("The file is not an assembly.")
            End If
        Catch ex As BadImageFormatException
            Console.WriteLine("The file is not an executable.")
        Catch ex As FileNotFoundException
            Console.WriteLine("The file cannot be found.")
        End Try
    End Sub
End Module
' Output:  
' Yes, the file is an Assembly.

Vea también