Ejemplo n.º 1
0
        /// <summary>
        /// Zip function calls Shell32, Interop.Shell32.dll is needed
        /// </summary>
        /// <param name="filesInFolder">Specify a folder containing the zip source files</param>
        /// <param name="zipFile">Specify the final zip file name, with ".zip" extension</param>
        public static void Compress(string filesInFolder, string zipFile)
        {
            if (filesInFolder == null || filesInFolder.Trim() == "")
            {
                return;
            }
            if (zipFile == null || zipFile.Trim() == "")
            {
                return;
            }
            if (!Directory.Exists(filesInFolder))
            {
                return;
            }

            DirectoryEx.DeleteEmptyDirectory(filesInFolder);

            Shell32.ShellClass sh = new Shell32.ShellClass();
            try
            {
                if (File.Exists(zipFile))
                {
                    File.Delete(zipFile);
                }
                //Create an empty zip file
                byte[] emptyzip = new byte[] { 80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

                FileStream fs = File.Create(zipFile);
                fs.Write(emptyzip, 0, emptyzip.Length);
                fs.Flush();
                fs.Close();

                Shell32.Folder      srcFolder  = sh.NameSpace(filesInFolder);
                Shell32.Folder      destFolder = sh.NameSpace(zipFile);
                Shell32.FolderItems items      = srcFolder.Items();
                destFolder.CopyHere(items, SHFILEOPSTRUCT.FOF_SILENT | SHFILEOPSTRUCT.FOF_NOCONFIRMATION);
                while (items.Count != destFolder.Items().Count)
                {
                    Thread.Sleep(50);
                }
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(sh);
            }
        }