Rob*_*ert 2 .net c# reflection
如何验证dll是否在.net中写入?我使用的代码如下:
Assembly assembly = null;
try
{
foreach (string fileName in Directory.GetFiles(Environment.CurrentDirectory.ToString(), "*.dll", SearchOption.TopDirectoryOnly))
{
try
{
assembly = Assembly.LoadFrom(fileName);
Console.WriteLine(fileName);
}
catch (Exception ex)
{
...
}
finally
{
...
}
}
}
catch (ReflectionTypeLoadException ex)
{
..
}
Run Code Online (Sandbox Code Playgroud)
当我想加载assembly = Assembly.LoadFrom(fileName)non.net dll时,会出现一个异常:
无法加载文件或程序集'file:/// ...'或其依赖项之一.该模块应该包含一个程序集清单.
我想在if-else子句中使用verify.你能帮助我吗?
您可以使用.NET引导程序DLL中的辅助函数.Mscoree.dll导出GetFileVersion(),它是一个返回程序集所需CLR版本的帮助程序.当文件不是程序集时,该函数将失败,并且不会引发异常.
它应该如下所示:
using System;
using System.Text;
using System.Runtime.InteropServices;
public class Utils {
public static bool IsNetAssembly(string path) {
var sb = new StringBuilder(256);
int written;
var hr = GetFileVersion(path, sb, sb.Capacity, out written);
return hr == 0;
}
[DllImport("mscoree.dll", CharSet = CharSet.Unicode)]
private static extern int GetFileVersion(string path, StringBuilder buffer, int buflen, out int written);
}
Run Code Online (Sandbox Code Playgroud)