﻿# 介紹好用工具：ILMerge (將多的 .NET 組件合併成單一組件)

當 .NET 專案開發越來越多的情況下，通常會有一大堆組件的情況，微軟提供一套 [ILMerge](https://www.nuget.org/packages/ILMerge/) 免費工具可以協助你將多個組件合併成單一個 .NET 組件，有效減少部署檔案的數量以及增加部署的彈性。

由於 [ILMerge](https://www.nuget.org/packages/ILMerge/) 是指令列工具，在安裝完成之後，所有檔案都放在 **C:\\Program Files\\Microsoft\\ILMerge** 目錄下，目錄下的 **ILMerge.doc** 檔案有完整的說明，以下是我閱讀完後的一些摘要筆記：

-   並非所有組件都能 Merge，例如有些組件包含 unmanaged code 就不一定能 Merge 成功，建議在 Merge 完後利用 [PEVerify](http://msdn.microsoft.com/zh-tw/library/62bwd2yd.aspx) 工具 (the .NET Framework SDK tool) 驗證輸出的組件是否有效。
-   執行 [ILMerge](https://www.nuget.org/packages/ILMerge/) 時的組件清單(input assemblies)的第一個**組件**為**主要組件**(primary assembly)，如果第一個組件為**執行檔(\*.exe)**，則 [ILMerge](https://www.nuget.org/packages/ILMerge/) 過的組件就會以此**組件**中定義的執行入口點(Main method)為主。
-   如果**主要組件**(primary assembly)有**強式名稱**簽章過，而且參數也有指定 **snk** 檔時，[ILMerge](https://www.nuget.org/packages/ILMerge/) 過後會自動重簽(re-signed)。

以下是一些使用範例：

1\. 將多個組件合併成一個，其中第一個組件為「主要組件」，通常是執行的主要程式

```
ILMerge.exe /out:Merged.Output.exe Assembly1.exe Assembly2.dll Assembly3.dll
```

2\. 將多個**類別庫組件**合併成一個，而且除了主要組件外，任何其他組件都不會公開給其他組件使用

```
ILMerge.exe /internalize /out:Merged.Output.dll Assembly1.dll Assembly2.dll
```

3\. 在合併完組件後重新利用強式名稱簽名過

```
ILMerge.exe /keyfile:my.snk /out:Merged.Output.dll Assembly1.dll Assembly2.dll
```

4\. 在組合的時候留下 ILMerge 的紀錄 ( 當 /log 參數不加上 **:Output.log** 則會將 Log 輸出到 Console )

```
ILMerge.exe /log:Output.log /out:Merged.Output.dll Assembly1.dll Assembly2.dll
```

如果不習慣用指令用工具的人也可以考慮使用 [ILMerge-GUI](https://github.com/jpdillingham/ILMergeGUI) 幫你組合組件，操作畫面友善許多，如下圖：

![ILMerge-GUI 1.0.0](https://stwillblogassets.blob.core.windows.net/files/images/external/stwillblogassets.blob.core.windows.net/76aa5e91ef09361c2d19-image_3.png "ILMerge-GUI 1.0.0")

使用上應該沒多大問題，就不再贅述了。

**相關連結**

-   [ILMerge - Microsoft Research](http://research.microsoft.com/en-us/people/mbarnett/ilmerge.aspx)
-   [Download details: ILMerge](https://www.nuget.org/packages/ILMerge/)
-   [ILMerge-GUI, the graphical interface for ILMerge](https://github.com/jpdillingham/ILMergeGUI)
-   [ILMerge-GUI at CodePlex](https://github.com/jpdillingham/ILMergeGUI)
-   [Merging .NET assemblies using ILMerge](http://www.codeproject.com/KB/dotnet/mergingassemblies.aspx)
-   [PEVerify 工具 (Peverify.exe)](http://msdn.microsoft.com/zh-tw/library/62bwd2yd.aspx)
-   [.NET Framework Developer Center](http://msdn.microsoft.com/en-us/netframework/aa496123.aspx) >  [Downloads](http://msdn.microsoft.com/en-us/netframework/aa569263.aspx) >  [Tools & Utilities](http://msdn.microsoft.com/en-us/netframework/aa569269.aspx)
-   [ASP.NET Merge Tool (Aspnet\_merge.exe)](http://msdn.microsoft.com/en-us/library/bb397866.aspx)
