プログラムを中心とした個人的なメモ用のブログです。 タイトルは迷走中。
内容の保証はできませんのであしからずご了承ください。

2017/11/30

Visual Studio のビルド後イベントで配布用の ZIP ファイルを自動生成する

update2017/12/05 event_note2017/11/30 1:29

Visual Studio で Relese ビルドを行うと、bin/Release に実行ファイル等が出力されます。
しかし、この中には不要なファイルもたくさんあるため、ビルド後イベントで必要なファイルだけを ZIP ファイルにするように処理を自動化しました。

尚、インストーラーを作成しないこのようなアプリケーションの配布を XCOPY 配置というようです。

環境

  • Visual Studio 2017

不要なファイルの削除と ZIP ファイル作成の自動化

不要なファイルを毎回手動で削除するのも大変なので、ビルド後イベントで処理します。
スクリプトは PowerShell で作成します。
不要なファイルを削除したらそのまま zip ファイルも作成します。

ビルド後イベント

ビルド後イベントの実行場所は出力フォルダになるので、プロジェクトルートに移動してからスクリプトを実行します。
また、Release ビルドのときのみ処理を実行するようにします。

if $(ConfigurationName) == Release (
cd $(ProjectDir)
powershell -ExecutionPolicy Unrestricted .\CreateZip.ps1 .\bin\Release .\bin\$(ProjectName).zip
)

PowerShell

*.xml *.pdb *.config を削除していますが、不要なファイルはプロジェクトに応じて適宜変更します。
私の場合、NLog を使用しているので、NLog.config は除外しています。

# CreateZip.ps1

# プロジェクトルートで実行すること
using namespace System.IO;
using namespace System.IO.Compression;

# source directory path (Release directory)
$sourceDir = $Args[0]
if (-not ($sourceDir)) { return 100 }

# target zip file path
$targetZipFile = $Args[1]
if (-not ($targetZipFile)) { return 101 }

# target zip file からディレクトリ名を取得
$parent = [Path]::GetDirectoryName($targetZipFile)
# target zip file を置くディレクトリがない場合は作成する
[Directory]::CreateDirectory($parent)
# 既に zip ファイルがある場合は削除しておく
[File]::Delete($targetZipFile)

# 一時ディレクトリ名
$tempDir = $parent + "\temp"
# Release ディレクトリから一時ディレクトリに丸ごとコピー
Copy-Item $sourceDir -destination $tempDir -recurse

# 一時ディレクトリから不要なファイルを削除(プロジェクトに応じて要変更)
Remove-Item -Recurse -path $tempDir -include *.pdb
Remove-Item -Recurse -path $tempDir -include *.xml
Remove-Item -Recurse -path $tempDir -include *.config -Exclude NLog.config

# アセンブリの読み込み
Add-Type -AssemblyName System.IO.Compression.FileSystem

# zip ファイル作成
[ZipFile]::CreateFromDirectory($tempDir, $targetZipFile)

# 一時ディレクトリ削除
Remove-Item -Recurse -path $tempDir

参考 URL