Merging a WPF application into a single EXE(WPF应用程序合并成单个Exe文件)

简介: I always dislike handing off little applications to people. Not because I can’t, but because of the steps involved to make sure it all just works.

I always dislike handing off little applications to people. Not because I can’t, but because of the steps involved to make sure it all just works. Small apps are the most problematic because I never want to take the time to create a whole installer project for just a few assemblies, and packaging up a zip file must be accompanied by “Unzip this into a folder in your programs directory and create a shortcut…” which brings us back to the whole installer business we started with.

There are a few tools already out there such as ILMerge by Microsoft Research (Which works great for most .NET-y things, but chokes on WPF applications) and a few paid tools by third party vendors that you could fork over a few hundred for to get. But, I’m a developer, which means I want to do it the Hard Way™. I did a little research and found the following blog posts on setting up and merging in DLL’s as resources into the main assembly and then extracting and loading them into memory when you run your application.

Links:

There were a few things I didn’t like about each solution. The first one (richarddingwall.name) ends up having you directly adding the .dll’s as resources directly. I hate maintaining things manually, especially when it will run fine on my machine but break when when I move it somewhere else because I forgot to update the resources when I added a new project. The one from blog.mahop.net builds on the previous one and changes the resolve location to a custom class with its own startup method. Better, because it resolves the resources earlier. Finally, the one from Daniel Chambers (digitallycreated.net) added in the final piece that automatically including the assemblies as resources. Unfortunately, the way he looks for culture specific assemblies didn’t work and I had to remove / change it to be closer to the one on mahop.net.

Final solution I’m currently using is as follows:

To the main executable project, unload and edit the .csproj file, and below the following line:

<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

Add this XML to the project file, save, and load it back up.

 <Target Name="AfterResolveReferences">
  <ItemGroup>
    <EmbeddedResource Include="@(ReferenceCopyLocalPaths)" Condition="'%(ReferenceCopyLocalPaths.Extension)' == '.dll'">
      <LogicalName>%(ReferenceCopyLocalPaths.DestinationSubDirectory)%(ReferenceCopyLocalPaths.Filename)%(ReferenceCopyLocalPaths.Extension)</LogicalName>
    </EmbeddedResource>
  </ItemGroup>
</Target>

It should look something like this when your done:

You’ll then add a new code file to the main project and add the following code to it (modified to fit how your application is named / structured, in a WPF application, a good place to put it would be App.xaml.cs):

[STAThread]
public static void Main()
{
    AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
 
    App.Main(); // Run WPF startup code.
}
 
private static Assembly OnResolveAssembly(object sender, ResolveEventArgs e)
{
    var thisAssembly = Assembly.GetExecutingAssembly();
 
    // Get the Name of the AssemblyFile
    var assemblyName = new AssemblyName(e.Name);
    var dllName = assemblyName.Name + ".dll";
 
    // Load from Embedded Resources - This function is not called if the Assembly is already
    // in the same folder as the app.
    var resources = thisAssembly.GetManifestResourceNames().Where(s => s.EndsWith(dllName));
    if (resources.Any())
    {
 
        // 99% of cases will only have one matching item, but if you don't,
        // you will have to change the logic to handle those cases.
        var resourceName = resources.First();
        using (var stream = thisAssembly.GetManifestResourceStream(resourceName))
        {
            if (stream == null) return null;
            var block = new byte[stream.Length];
 
            // Safely try to load the assembly.
            try
            {
                stream.Read(block, 0, block.Length);
                return Assembly.Load(block);
            }
            catch (IOException)
            {
                return null;
            }
            catch(BadImageFormatException)
            {
                return null;
            }
        }
    }
 
    // in the case the resource doesn't exist, return null.
    return null;
}

Finally, make sure you update the target method for your main application to be the main method for the project you just added:

And, that’s it!

When you build your application you’ll still see all the assemblies in the output directory, but you should be able to take just the executable, move it somewhere else, and run it just as it is.

目录
相关文章
|
5月前
|
XML 开发框架 .NET
|
C#
WPF 4 Ribbon 开发 之 应用程序菜单(Application Menu)
原文:WPF 4 Ribbon 开发 之 应用程序菜单(Application Menu)      在上一篇中我们完成了快捷工具栏的开发,本篇将讲解应用程序菜单开发的相关内容。如下图所示,点击程序窗口左上角的记事本图标(Application Button)会显示出应用程序菜单(Application Menu)列表,列表中的按键即为软件的一些基本功能。
2117 0
|
C# 前端开发 Windows
WPF中的Application类。
原文:WPF中的Application类。 Application对象用的名称空间是system.windows 1、手动创建Application对象步骤。 1.1)、把项目中的App.Xaml文件从项目中排除。
1232 0
|
C#
WPF整理-Mutex确保Application单例运行
原文:WPF整理-Mutex确保Application单例运行 有时我们不希望我们的WPF应用程序可以同时运行有多个实例,当我们试图运行第二个实例的时候,已经运行的实例也应该弹出来。 我们可以用Mutex来实现 打开App.
1313 0
|
C# Windows
WPF Application 类介绍以及怎样修改启动方式
    因为想要修改wpf的启动方式,所以研究了下Application类,现把一些有用的属性与大家分享下: 属性:     Current                  获取当前 AppDomain的 Application 对象     MainWindow           获取或设置应用程序的主窗体。
830 0
|
28天前
|
C# 开发者 Windows
基于Material Design风格开源、易用、强大的WPF UI控件库
基于Material Design风格开源、易用、强大的WPF UI控件库
|
5月前
|
C#
浅谈WPF之装饰器实现控件锚点
使用过visio的都知道,在绘制流程图时,当选择或鼠标移动到控件时,都会在控件的四周出现锚点,以便于修改大小,移动位置,或连接线等,那此功能是如何实现的呢?在WPF开发中,想要在控件四周实现锚点,可以通过装饰器来实现,今天通过一个简单的小例子,简述如何在WPF开发中,应用装饰器,仅供学习分享使用,如有不足之处,还请指正。
66 1
|
9月前
|
C# Windows
WPF技术之图形系列Polygon控件
WPF Polygon是Windows Presentation Foundation (WPF)框架中的一个标记元素,用于绘制多边形形状。它可以通过设置多个点的坐标来定义多边形的形状,可以绘制任意复杂度的多边形。
467 0