网上很多例子,各种套路,就是没有测试过。
WPF 将DLL嵌入EXE文件的套路是这样的
1.将要引用的dll源文件添加到wpf 项目中,dll 的属性-》生成操作为【嵌入的资源】。
2.监听 AppDomain.CurrentDomain.AssemblyResolve 事件
监听的事件的位置很重要,跟wpf 的运行顺序有关系吧。
找到wpf 项目中的App.xaml 文件,App.xaml.cs 类的构造函数中监听。
1 public App() 2 { 3 4 CatchException(); 5 AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly; 6 }
1 private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args) 2 { 3 var requestedAssemblyName = new AssemblyName(args.Name); 4 string resourceName = "当前项目的命名空间" + "." + requestedAssemblyName.Name + ".dll"; 5 System.Windows.Forms.MessageBox.Show(resourceName); 6 try 7 { 8 using (System.IO.Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) 9 { 10 byte[] buffer = new byte[stream.Length]; 11 stream.Read(buffer, 0, buffer.Length); 12 return Assembly.Load(buffer); 13 } 14 } 15 catch (Exception ex) 16 { 17 System.Windows.Forms.MessageBox.Show(String.Format(@"{0}{1}",ex.Message,ex.StackTrace)); 18 throw; 19 } 20 }
参考了一下链接
http://www.codeproject.com/Articles/310675/AppDomain-AssemblyResolve-Event-Tips
http://www.digitallycreated.net/Blog/61/combining-multiple-assemblies-into-a-single-exe-for-a-wpf-application
http://www.cnblogs.com/luoshupeng/p/3951597.html
http://www.cnblogs.com/xiashengwang/archive/2012/07/16/2593921.html