msbuildzipmsbuildcommunitytasks

MSBuild zip directories task without any external dependencies (no MSBuildCommunityTasks)


I have attempted to find a way to zip a build up using MSBuild without using MSBuildCommunityTasks. I did manage to find some code online but it seems to take all the files, even ones in directories and put it in one file (no directories).

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<UsingTask TaskName="Zip" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup>
  <InputFileNames ParameterType="Microsoft.Build.Framework.ITaskItem[]" Required="true" />
  <OutputFileName ParameterType="System.String" Required="true" />
  <OverwriteExistingFile ParameterType="System.Boolean" Required="false" />
</ParameterGroup>
<Task>
  <Reference Include="System.IO.Compression" />
  <Using Namespace="System.IO.Compression" />
  <Code Type="Fragment" Language="cs">
  <![CDATA[ 
    const int BufferSize = 64 * 1024;

    var buffer = new byte[BufferSize];
    var fileMode = OverwriteExistingFile ? FileMode.Create : FileMode.CreateNew;

    using (var outputFileStream = new FileStream(OutputFileName, fileMode))
    {
      using (var archive = new ZipArchive(outputFileStream, ZipArchiveMode.Create))
      {
        foreach (var inputFileName in InputFileNames.Select(f => f.ItemSpec))
        {
          var archiveEntry = archive.CreateEntry(Path.GetFileName(inputFileName));

          using (var fs = new FileStream(inputFileName, FileMode.Open))
          {
            using (var zipStream = archiveEntry.Open())
            {
              int bytesRead = -1;
              while ((bytesRead = fs.Read(buffer, 0, BufferSize)) > 0)
              {
                zipStream.Write(buffer, 0, bytesRead);
              }
            }
          }
        }
      }
    }        
  ]]>
  </Code>
</Task>
</UsingTask>
</Project>

How can i get this code to zip up my folder and keep the directories intact?


Solution

  • <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
      <UsingTask TaskName="Zip" TaskFactory="CodeTaskFactory" AssemblyName="Microsoft.Build.Tasks.v12.0">
        <ParameterGroup>
          <Directory ParameterType="System.String" Required="true" />
        </ParameterGroup>
        <Task>
          <Reference Include="System.IO.Compression.FileSystem" />
          <Code>System.IO.Compression.ZipFile.CreateFromDirectory(Directory, Directory + ".zip");</Code>
        </Task>
      </UsingTask>
    
      <Target Name="Foo">
        <Zip Directory="C:\Users\Ilya.Kozhevnikov\Dropbox\Foo" />
      </Target>
    </Project>