闽公网安备 35020302035485号
程序集是经由编译器编译得到的,供 CLR 进一步编译执行的那个中间产物。它一般表现为 .dll 或者是 .exe 的格式,但是要注意,它们跟普通意义上的 WIN32 可执行程序是完全不同的东西,程序集必须依靠 CLR 才能顺利执行。程序集是 .NET 编程的基本组成部分。
如何使用编程方式判断一个文件是否为程序集
1.使用 AssemblyName3.如果引发 BadImageFormatException 异常,则该文件不是程序集。
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");
// 堆代码 duidaima.com
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 方法会先加载测试文件,然后在读取信息后释放。6.检查 IsAssembly 属性值。如果为 false ,则该文件不是程序集。
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.
*/
}