今天遇到一个问题,就是在要肯定一个C#项目中正在使用的一个dll文件是什么模式编译的。由于Debug和Release两种模式编译出的DLL,混用会有必定的风险。我在网上查了一些资料,最终找到了这篇文章:工具
http://www.codeproject.com/Articles/72504/NET-Determine-Whether-an-Assembly-was-compiled-in测试
这篇文章里给出了两个方法检查dll文件是哪一个模式下编译的,第一个方法是用.NET提供的反编译工具ildasm。但我编译了一组dll测试了一下,这种找特征的方法并非每次有效,所以我主要写了个小工具实现了第二个方法。ui
创建C#窗体应用程序(Winform)以下:spa
程序代码以下:code
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DebugReleaseTestor { public partial class FormMain : Form { public FormMain() { InitializeComponent(); } /// <summary> /// 测试指定文件是否为Debug模式编译 /// </summary> /// <param name="filepath"></param> /// <returns></returns> private bool IsAssemblyDebugBuild(string filepath) { Assembly assembly = Assembly.LoadFile(Path.GetFullPath(filepath)); return assembly.GetCustomAttributes(false).Any(x => (x as DebuggableAttribute) != null ? (x as DebuggableAttribute).IsJITTrackingEnabled : false); } /// <summary> /// 按钮:查找文件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnBrowse_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.CheckFileExists = true; ofd.CheckPathExists = true; ofd.Multiselect = false; ofd.DefaultExt = "dll"; ofd.Filter = "dll文件|*.dll|全部文件|*.*"; if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { txtFilePath.Text = ofd.FileName; } } /// <summary> /// 按钮:测试指定文件是否为Debug模式编译 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnScan_Click(object sender, EventArgs e) { try { string result = ""; string filePath = txtFilePath.Text; if (File.Exists(filePath)) { if (IsAssemblyDebugBuild(filePath)) { result = "这是一个[DEBUG]模式下编译的DLL文件"; } else { result = "这是一个[RELEASE]模式下编译的DLL文件"; } } else { result = "文件不存在"; } txtResult.Text = result; } catch (Exception ex) { txtResult.Text = ex.Message; } } } }
程序运行效果以下:orm
一、检测到dll文件是在Debug模式下编译的get
二、 检测到dll文件是在Release模式下编译的string
三、不是C#(或VB.NET等) 语言生成的dll,工具会直接提示异常信息it
小工具的下载地址:http://pan.baidu.com/s/1gfjT2ltio
END