如何使用 C# 判断一个文件是否为程序集
程序集是經由編譯器編譯得到的,供 CLR 進一步編譯執行的那個中間產物。它一般表現為 .dll 或者是 .exe 的格式,但是要注意,它們跟普通意義上的 WIN32 可執行程序是完全不同的東西,程序集必須依靠 CLR 才能順利執行。程序集是 .NET 編程的基本組成部分。
如何手動確認一個文件是否為程序集
啟動 IL 反匯編程序(如 Ildasm.exe 或者 ILSpy)。
載入你想測試的文件。
如果可以正常載入顯示了程序集信息,則說明為程序集。如果提示 “that the file is not a portable executable (PE) file” 則表示該文件不是程序集文件。
如何使用編程方式判斷一個文件是否為程序集
使用 AssemblyName
調用 AssemblyName.GetAssemblyName 方法,傳遞測試文件的完整路徑。
如果引發 BadImageFormatException 異常,則該文件不是程序集。
此示例測試 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. */ }GetAssemblyName 方法會先加載測試文件,然后在讀取信息后釋放。
使用 PEReader
安裝 NuGet 包 :System.Reflection.Metadata
創建一個 System.IO.FileStream 實例,用于從測試文件讀取數據。
創建一個 System.Reflection.PortableExecutable.PEReader 實例,并把文件流傳遞給構造函數。、
檢查 HasMetadata 屬性值。如果為?
false
?,則該文件不是程序集。
調用 PEReader 實例的 GetMetadataReader 方法,創建一個元數據讀取器。
檢查 IsAssembly 屬性值。如果為?
false
?,則該文件不是程序集。
與 GetAssemblyName 方法不同,PEReader 不會在本機可移植可執行文件(PE)上引發異常。這使您能夠在需要檢查此類文件時避免異常導致的額外性能成本。如果文件不存在或不是PE文件,您仍然需要處理異常。
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. */ }總結
以上是生活随笔為你收集整理的如何使用 C# 判断一个文件是否为程序集的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .NET Core Runtime vs
- 下一篇: 【翻译】C#表达式中的动态查询