My Brain on Code

NAnt Zip Task and Passwords

Recently I needed to password protect a zip file created using NAnt. Unfortunately, it didn’t ship this feature right out of the box, so I modified the NAnt source to fit my needs. Here’s what I did:

I downloaded the NAnt source from the NAnt website

I then opened the solution up in Visual Studio 2008 (that’s my default VS IDE). I had to go through the project upgrade wizard. Everything converted without any errors

The portion that contains the zip task was located in the NAnt.Compression project. There was a Tasks folder with a ZipTask.cs file so I opened that up. In order to specify a password within the nant task you must add a TaskAttribute like so:

private string _password;  
/// <summary>  
/// The password for the file.  
/// </summary>  
public string Password {  
    get { return _password; }  
    set { _password = StringUtils.ConvertEmptyToNull(value); }  

This allows you to specify a password within the nant task like this:

<zip zipfile="" password="secret">  
    <fileset basedir="${bin.dir}" prefix="bin">  
        <include name="**/*" />  
    <fileset basedir="${doc.dir}" prefix="doc">  
        <include name="**/*" />  

NAnt uses the #ziplib for zipping files. So to actually use the password for the zip file we must modify the ExecuteTask() method. This method is where all the action happens when the zip task is executed. Fortunately it was pretty simple to add the password (NOTE: I omitted the rest of the ExecuteTask() method for brevity):

protected override void ExecuteTask() {  
    ZipOutputStream zOutstream = null;  
    Log(Level.Info, "Zipping {0} files to {1}.",  
                ZipFileSets.FileCount, ZipFile.FullName);  
    try {  
        // set encoding to use for filenames and comment  
        ZipConstants.DefaultCodePage = Encoding.CodePage;  
        zOutstream = new ZipOutputStream(ZipFile.Create());  
        // set compression level  
        // set comment  
        if (!StringUtils.IsNullOrEmpty(Comment)) {  
        // set password  
        if (!StringUtils.IsNullOrEmpty(Password)) {  
            zOutstream.Password = Password;  
        // omitted for brevity  

After all of this, I simply Rebuilt the NAnt.Compression project. I tried to rebuild the entire solution, however, I was getting errors in VS. Rebuilding just the project worked though

Once rebuilt, the NAnt.Compression.dll is located within the “NAnt.Compression” folder which is located in the “build.VS.NET” folder. I simply copied the NAnt.CompressionTasks.dll and the NAnt.CompressionTasks.xml file and dropped them into my main NAnt folder (e.g. C:\Programming\NAnt\bin ). After that, I could use the password attribute to password protect zip files made using NAnt!