peteris.rocks

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.

MSBuild

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

<UsingTask TaskName="Zip" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
  <ParameterGroup>
    <OutputFilename ParameterType="System.String" Required="true" />
    <Files ParameterType="Microsoft.Build.Framework.ITaskItem[]" Required="true" />
  </ParameterGroup>
  <Task>
    <Reference Include="System.IO.Compression" />
    <Using Namespace="System.IO.Compression" />
    <Code Type="Fragment" Language="cs">
    <![CDATA[
      try
      {
        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())
                    fileStream.CopyTo(fileStreamInZip);
            }
        }
        return true;
      }
      catch (Exception ex)
      {
        Log.LogErrorFromException(ex);
        return false;
      }
    ]]>
    </Code>
  </Task>
</UsingTask>

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" />
  <ItemGroup>
    <ZipFiles Include="$(OutputPath)Project.dll" />
    <ZipFiles Include="$(OutputPath)Project.pdb" />
    <ZipFiles Include="$(OutputPath)Project.License.txt" />
  </ItemGroup>
  <Zip OutputFilename="$(OutputPath)Project.zip" Files="@(ZipFiles)" />
</Target>

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"/>
  </CreateItem>
  <Zip ZipFileName="YourZipFile.zip" WorkingDirectory="YourSourceFolder" Files="@(ZipFiles)" />
</Target>