다음을 통해 공유


방법: 파일이 어셈블리인지 확인

파일은 관리되는 경우에만 어셈블리이며 해당 메타데이터에 어셈블리 항목을 포함합니다. 어셈블리 및 메타데이터에 대한 자세한 내용은 어셈블리 매니페스트를 참조하세요.

파일이 어셈블리인지 수동으로 확인하는 방법

  1. Ildasm.exe(IL 디스어셈블러) 도구를 시작합니다.

  2. 테스트할 파일을 로드합니다.

  3. ILDASM에서 파일이 PE(이식 가능한 실행 파일) 파일이 아니라고 보고하는 경우 어셈블리가 아닙니다. 자세한 내용은 방법 : 어셈블리 콘텐츠 보기 항목을 참조하세요.

파일이 어셈블리인지 프로그래밍 방식으로 확인하는 방법

AssemblyName 클래스 사용

  1. 메서드를 AssemblyName.GetAssemblyName 호출하여 테스트할 파일의 전체 파일 경로와 이름을 전달합니다.

  2. 예외가 발생하면 파일이 어셈블리가 아닙니다.

이 예제에서는 DLL을 테스트하여 어셈블리인지 확인합니다.

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.  

메서드는 GetAssemblyName 테스트 파일을 로드한 다음 정보를 읽은 후 해제합니다.

PEReader 클래스 사용

주의

PEReaderSystem.Reflection.Metadata 라이브러리는 신뢰할 수 없는 입력을 처리하도록 설계되지 않았습니다. 형식이 잘못되었거나 악의적인 PE 파일은 범위를 벗어난 메모리 액세스, 충돌 또는 중단을 포함하여 예기치 않은 동작을 일으킬 수 있습니다. 신뢰할 수 있는 어셈블리에서만 이러한 API를 사용합니다.

  1. .NET Standard 또는 .NET Framework를 대상으로 하는 경우 System.Reflection.Metadata NuGet 패키지를 설치합니다. (.NET Core 또는 .NET 5+를 대상으로 하는 경우 이 라이브러리가 공유 프레임워크에 포함되어 있으므로 이 단계가 필요하지 않습니다.)

  2. System.IO.FileStream 테스트 중인 파일에서 데이터를 읽을 인스턴스를 만듭니다.

  3. 인스턴스를 System.Reflection.PortableExecutable.PEReader 만들어 파일 스트림을 생성자에 전달합니다.

  4. 속성 값을 확인합니다 HasMetadata . 값이 false면 파일이 어셈블리가 아닙니다.

  5. PE 판독기 GetMetadataReader 인스턴스에서 메서드를 호출하여 메타데이터 판독기를 만듭니다.

  6. 속성 값을 확인합니다 IsAssembly . 값이 true면 파일이 어셈블리입니다.

있기 GetAssemblyName 메서드와 달리, PEReader 클래스는 네이티브 이식 가능한 실행 파일(PE)에 대해 예외를 throw하지 않습니다. 이렇게 하면 이러한 파일을 확인해야 할 때 예외로 인한 추가 성능 비용을 방지할 수 있습니다. 파일이 없거나 PE 파일이 아닌 경우에도 예외를 처리해야 합니다.

이 예제에서는 클래스를 사용하여 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.

참고하십시오