Instrukcje: określanie, czy plik jest zestawem

Plik jest zestawem, jeśli i tylko wtedy, gdy jest zarządzany, i zawiera wpis zestawu w metadanych. Aby uzyskać więcej informacji na temat zestawów i metadanych, zobacz Manifest zestawu.

Jak ręcznie określić, czy plik jest zestawem

  1. Uruchom narzędzie Ildasm.exe (dezasembler IL).

  2. Załaduj plik, który chcesz przetestować.

  3. Jeśli program ILDASM zgłasza, że plik nie jest przenośnym plikiem wykonywalnym (PE), to nie jest to zestaw. Aby uzyskać więcej informacji, zobacz temat Instrukcje: Wyświetlanie zawartości zestawu.

Jak programowo określić, czy plik jest zestawem

Korzystanie z klasy AssemblyName

  1. Wywołaj metodę AssemblyName.GetAssemblyName , przekazując pełną ścieżkę pliku i nazwę testowego pliku.

  2. Jeśli zgłaszany BadImageFormatException jest wyjątek, plik nie jest zestawem.

W tym przykładzie testuje bibliotekę DLL, aby sprawdzić, czy jest to zestaw.

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.  

Metoda GetAssemblyName ładuje plik testowy, a następnie zwalnia go po odczytaniu informacji.

Korzystanie z klasy PEReader

  1. Jeśli używasz platformy .NET Standard lub .NET Framework, zainstaluj plik System.EmocjeJonów. Pakiet NuGet metadanych. (W przypadku określania platformy .NET Core lub .NET 5+, ten krok nie jest wymagany, ponieważ ta biblioteka jest zawarta w strukturze udostępnionej).

  2. System.IO.FileStream Utwórz wystąpienie do odczytu danych z pliku, który testujesz.

  3. System.Reflection.PortableExecutable.PEReader Utwórz wystąpienie, przekazując strumień plików do konstruktora.

  4. Sprawdź wartość HasMetadata właściwości. Jeśli wartość to false, plik nie jest zestawem.

  5. Wywołaj metodę GetMetadataReader w wystąpieniu czytnika PE, aby utworzyć czytnik metadanych.

  6. Sprawdź wartość IsAssembly właściwości. Jeśli wartość to true, plik jest zestawem.

GetAssemblyName W przeciwieństwie do metody PEReader klasa nie zgłasza wyjątku w natywnych plikach przenośnych plików wykonywalnych (PE). Dzięki temu można uniknąć dodatkowych kosztów wydajności spowodowanych wyjątkami, gdy trzeba sprawdzić takie pliki. Nadal trzeba obsługiwać wyjątki w przypadku, gdy plik nie istnieje lub nie jest plikiem PE.

W tym przykładzie pokazano, jak określić, czy plik jest zestawem PEReader przy użyciu klasy .

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.

Zobacz też