HOW TO:判斷檔案是否為組件 (C# 和 Visual Basic)

檔案必須是 Managed,而且其中繼資料也必須包含組件項目時,才會視為是組件。 如需組件和中繼資料的詳細資訊,請參閱組件資訊清單主題。

如何以人工方式判斷檔案是否為組件

  1. 啟動 Ildasm.exe (MSIL 反組譯工具)

  2. 載入要測試的檔案。

  3. 如果 ILDASM 回報該檔案並非可攜式執行檔 (PE),則檔案不是組件。 如需詳細資訊,請參閱HOW TO:檢視組件內容主題。

如何以程式方式判斷檔案是否為組件

  1. 呼叫 GetAssemblyName 方法,並傳遞測試檔案的完整檔案路徑和檔案名稱。

  2. 如果擲回 BadImageFormatException 例外狀況,則檔案不是組件。

範例

下面範例會測試一個 DLL,查看這個檔案是否為組件。

Module Module1
    Sub Main()
        Try
            Dim testAssembly As Reflection.AssemblyName =
                                Reflection.AssemblyName.GetAssemblyName("C:\Windows\Microsoft.NET\Framework\v3.5\System.Net.dll")
            Console.WriteLine("Yes, the file is an Assembly.")
        Catch ex As System.IO.FileNotFoundException
            Console.WriteLine("The file cannot be found.")
        Catch ex As System.BadImageFormatException
            Console.WriteLine("The file is not an Assembly.")
        Catch ex As System.IO.FileLoadException
            Console.WriteLine("The Assembly has already been loaded.")
        End Try
        Console.ReadLine()
    End Sub
End Module
' Output (with .NET Framework 3.5 installed):
'        Yes, the file is an Assembly.
class TestAssembly
{
    static void Main()
    {

        try
        {
            System.Reflection.AssemblyName testAssembly =
                System.Reflection.AssemblyName.GetAssemblyName(@"C:\Windows\Microsoft.NET\Framework\v3.5\System.Net.dll");

            System.Console.WriteLine("Yes, the file is an assembly.");
        }

        catch (System.IO.FileNotFoundException)
        {
            System.Console.WriteLine("The file cannot be found.");
        }

        catch (System.BadImageFormatException)
        {
            System.Console.WriteLine("The file is not an assembly.");
        }

        catch (System.IO.FileLoadException)
        {
            System.Console.WriteLine("The assembly has already been loaded.");
        }
    }
}
/* Output (with .NET Framework 3.5 installed):
    Yes, the file is an assembly.
*/

GetAssemblyName 方法會載入測試檔案,並在讀取資訊後將其釋出。

請參閱

參考

AssemblyName

概念

C# 程式設計手冊

組件和全域組件快取 (C# 和 Visual Basic)

其他資源

Visual Basic 程式設計手冊