Creating Release .zip Archive with MSBuild

Last updated on

Suppose you want to automatically create a .zip archive with your program, license file and other data.


Add this to your Project.csproj file in <Project>

<UsingTask TaskName="Zip" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
    <OutputFilename ParameterType="System.String" Required="true" />
    <Files ParameterType="Microsoft.Build.Framework.ITaskItem[]" Required="true" />
    <Reference Include="System.IO.Compression" />
    <Using Namespace="System.IO.Compression" />
    <Code Type="Fragment" Language="cs">
        using (Stream zipStream = new FileStream(Path.GetFullPath(OutputFilename), FileMode.Create, FileAccess.Write))
        using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create))
            foreach (ITaskItem fileItem in Files)
                string filename = fileItem.ItemSpec;
                using (Stream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read))
                using (Stream fileStreamInZip = archive.CreateEntry(new FileInfo(filename).Name).Open())
        return true;
      catch (Exception ex)
        return false;

This is how easy it is to write your own custom build tasks in C#.

Add this in <Project>

<Target Name="AfterBuild" Condition="$(Configuration) == 'Release'">
  <Copy SourceFiles="$(SolutionDir)\License.txt" DestinationFiles="$(OutputPath)Project.License.txt" />
    <ZipFiles Include="$(OutputPath)Project.dll" />
    <ZipFiles Include="$(OutputPath)Project.pdb" />
    <ZipFiles Include="$(OutputPath)Project.License.txt" />
  <Zip OutputFilename="$(OutputPath)" Files="@(ZipFiles)" />

This will create a .zip for Release builds. It'll copy License.txt from the solution directory and create an archive with the library dll, license file and also debugging symbols.

If you're using versioning with MSBuild you could also use add a version number Project-$(Version).zip.

MSBuild Community Tasks

An alternative approach is to use MSBuild Community Tasks

Non-related example

<Import Project="lib\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets" />
<Target Name="Zip">
  <CreateItem Include="YourSourceFolder\*.*" >
      <Output ItemName="ZipFiles" TaskParameter="Include"/>
  <Zip ZipFileName="" WorkingDirectory="YourSourceFolder" Files="@(ZipFiles)" />