Compartir a través de


Cómo: Determinar si un archivo es un ensamblado

Un archivo es un ensamblado si y solo si se administra y contiene una entrada de ensamblado en sus metadatos. Para obtener más información sobre ensamblados y metadatos, vea Manifiesto de 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 desea probar.

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

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

Uso de la clase AssemblyName

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

  2. Si se produce una BadImageFormatException excepción, 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 GetAssemblyName método carga el archivo de prueba y, a continuación, lo libera una vez que se lee la información.

Uso de la clase PEReader

Precaución

PEReader y la System.Reflection.Metadata biblioteca no están diseñadas para manejar la entrada que no es de confianza. Los archivos PE malformados o malintencionados pueden provocar un comportamiento inesperado, incluido el acceso a memoria sin límites, bloqueos o cuelgues. Usa solo estas APIs con ensamblados confiables.

  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 System.IO.FileStream instancia para leer datos del archivo que está probando.

  3. Cree una instancia de System.Reflection.PortableExecutable.PEReader y pase su flujo de archivos al constructor.

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

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

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

A diferencia del GetAssemblyName método , la PEReader clase no produce una excepción en archivos ejecutables portables (PE) nativos. Esto le permite evitar el costo de rendimiento adicional causado por excepciones cuando necesite comprobar dichos archivos. Todavía tiene que manejar 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 PEReader clase .

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.

Consulte también