none
How to create password protected ZIP file in C#?

    Question

  • Hi Everybody!

     

    I want to create a ZIP file which is password protected. Later on I want to UNZIP it using the same password that was used to ZIP. Can anybody help me out? Highly appreciated!!

     

    Thanks

    Wednesday, December 05, 2007 6:49 PM

Answers

  • I tried them two ways, the first creates ZIP file but I didn't see anyway to password protect the file. The second creates a ZIP file but gives error when trying to open the zip file. Also, the second one doesn't have any way to password protect the file. I am really waiting for it, I really need it as soon as possible. Please help me:

     

     

    THe first is:

    public static void ZipIT()

    {

    // Put user code to initialize the page here

    FileStream objFile;

    string strFile;

    String[] strFileNames = new String[3] { "h:/File1.txt", "h:/File2.txt", "h:/File3.txt" };

    CRC32 objCRC32 = new CRC32();

    objFile = File.Create("h:/ZipFile.zip",100,FileOptions.Encrypted,System.Security.AccessControl.FileSecurity);

    objFile.Close();

    ZipOutputStream zipFile = new ZipOutputStream(new java.io.FileOutputStream(objFile.Name));

    zipFile.setLevel(6);

    foreach (string file in strFileNames)

    {

    FileStream fs = File.OpenRead(file);

    byte[] buffer = new byte[fs.Length - 1];

    sbyte[] buffer1 = new sbyte[fs.Length - 1];

    strFile = file.Substring(file.LastIndexOf("/") + 1);

    fs.Read(buffer, 0, buffer.Length);

    ZipEntry objZipEntry = new ZipEntry(strFile);

    java.io.FileInputStream from = new java.io.FileInputStream(file);

    zipFile.putNextEntry(objZipEntry);

    CopyStream(from, zipFile);

    objZipEntry.setMethod(ZipEntry.DEFLATED);

    fs.Close();

    zipFile.closeEntry();

    }

    zipFile.flush();

    zipFile.close();

    objFile.Close();

    }

    public static void CopyStream(java.io.InputStream from, java.io.OutputStream to)

    {

    sbyte[] buffer = new sbyte[8192];

    int got;

    while ((got = from.read(buffer, 0, buffer.Length)) > 0)

    to.write(buffer, 0, got);

    }

     

    and the next is:

    FileStream sourceFile = null;

    FileStream destFile = null;

    public void ZipIt(string zipFileName, string srceFile)

    {

    sourceFile = File.OpenRead(srceFile);

    destFile = File.Create(zipFileName);

    GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress);

    try

    {

    int theByte = sourceFile.ReadByte();

    while (theByte != -1)

    {

    compStream.WriteByte((byte)theByte);

    theByte = sourceFile.ReadByte();

    }

    }

    finally

    {

    compStream.Dispose();

    }

    Wednesday, December 05, 2007 7:58 PM

All replies

  • I tried them two ways, the first creates ZIP file but I didn't see anyway to password protect the file. The second creates a ZIP file but gives error when trying to open the zip file. Also, the second one doesn't have any way to password protect the file. I am really waiting for it, I really need it as soon as possible. Please help me:

     

     

    THe first is:

    public static void ZipIT()

    {

    // Put user code to initialize the page here

    FileStream objFile;

    string strFile;

    String[] strFileNames = new String[3] { "h:/File1.txt", "h:/File2.txt", "h:/File3.txt" };

    CRC32 objCRC32 = new CRC32();

    objFile = File.Create("h:/ZipFile.zip",100,FileOptions.Encrypted,System.Security.AccessControl.FileSecurity);

    objFile.Close();

    ZipOutputStream zipFile = new ZipOutputStream(new java.io.FileOutputStream(objFile.Name));

    zipFile.setLevel(6);

    foreach (string file in strFileNames)

    {

    FileStream fs = File.OpenRead(file);

    byte[] buffer = new byte[fs.Length - 1];

    sbyte[] buffer1 = new sbyte[fs.Length - 1];

    strFile = file.Substring(file.LastIndexOf("/") + 1);

    fs.Read(buffer, 0, buffer.Length);

    ZipEntry objZipEntry = new ZipEntry(strFile);

    java.io.FileInputStream from = new java.io.FileInputStream(file);

    zipFile.putNextEntry(objZipEntry);

    CopyStream(from, zipFile);

    objZipEntry.setMethod(ZipEntry.DEFLATED);

    fs.Close();

    zipFile.closeEntry();

    }

    zipFile.flush();

    zipFile.close();

    objFile.Close();

    }

    public static void CopyStream(java.io.InputStream from, java.io.OutputStream to)

    {

    sbyte[] buffer = new sbyte[8192];

    int got;

    while ((got = from.read(buffer, 0, buffer.Length)) > 0)

    to.write(buffer, 0, got);

    }

     

    and the next is:

    FileStream sourceFile = null;

    FileStream destFile = null;

    public void ZipIt(string zipFileName, string srceFile)

    {

    sourceFile = File.OpenRead(srceFile);

    destFile = File.Create(zipFileName);

    GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress);

    try

    {

    int theByte = sourceFile.ReadByte();

    while (theByte != -1)

    {

    compStream.WriteByte((byte)theByte);

    theByte = sourceFile.ReadByte();

    }

    }

    finally

    {

    compStream.Dispose();

    }

    Wednesday, December 05, 2007 7:58 PM
  • Donno if this help or if this is too late. I included a third party zip library (ICSharpCode.SharpZipLib.Zip), then use the following code and it works for me.

    Note:
    1) The 3rd party software is open source so you are free to look at what they did.
    2) The code below was actually just modifying their example code abit. In case you think I wrote it. Stick out tongue

           public void genZipFile(string filename, string pwd)
            {
                string zipFileName;
                string fileExt;
               
                try
                {
                    fileExt = Path.GetExtension(filename);
                    zipFileName = filename.Replace(fileExt, ".zip");
                    using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFileName)))
                    {
                        s.Password = pwd;
                        s.SetLevel(4); // 0 - store only to 9 - means best compression

                        byte[] buffer = new byte[4096];

                        ZipEntry entry = new ZipEntry(Path.GetFileName(filename));
                        entry.DateTime = DateTime.Now;
                        s.PutNextEntry(entry);

                        using (FileStream fs = File.OpenRead(filename))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                s.Write(buffer, 0, sourceBytes);
                            } while (sourceBytes > 0);
                        }
                        s.Finish();

                        s.Close();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception during processing {0}", ex);
                }
            }
    Monday, March 31, 2008 2:53 AM
  • You can do it with DotNetZip, too.  It's an add-on library available from www.codeplex.com/DotNetZip  .

    Example code:

       try
       {
         using (ZipFile zip = new ZipFile("MyZipFile.zip")
         {
           zip.Password("Secret1!");
           zip.AddFile("c:\\photos\\personal\\7440-N49th.png");
           zip.AddFile("c:\\Desktop\\2005_Annual_Report.pdf");
           zip.AddFile("ReadMe.txt");
           zip.Save();
         }
       }
       catch (System.Exception ex1)
       {
         System.Console.Error.WriteLine("exception: " + ex1);
       }
    


    In this case, the entries themselves are password protected. The Zip spec allows you to password-protect (encrypt) the entries in the zipfile, and also separately allows the possibility of password-protecting the list of files. In this case it is the entries themselves that are protected. This is the typical case when you get a zipfile - you can see the list of files but you can only extract the files if you know the password.

    • Edited by cheeso Thursday, June 05, 2008 3:02 PM reformat the code
    • Proposed as answer by N L V Saturday, October 03, 2009 6:24 AM
    Thursday, June 05, 2008 3:01 PM
  • An easy way is using the Ultimate ZIP Component for .NET. Information about this library can also be found at its web blog.
    Thursday, April 22, 2010 9:23 PM