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

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

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

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

  2. 테스트하려는 파일을 로드합니다.

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

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

AssemblyName 클래스 사용

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

  2. BadImageFormatException 예외가 throw되는 경우 파일이 어셈블리가 아닙니다.

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

  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.

참고 항목