Login Login
MORE

WIDGETS

Widgets

Wanted articles
Who is online?
Article tools

Difference between revisions of "CSharp:SharpZip"

From Aino Wiki

Jump to: navigation, search
(Sharp Zip)
 
Line 6: Line 6:
 
</pre>
 
</pre>
  
=Esempio=
+
==Esempio==
==Nella Classe Helper==
+
===Nella Classe Helper===
 
<syntaxhighlight lang="csharp">
 
<syntaxhighlight lang="csharp">
 
using ICSharpCode.SharpZipLib.Core;
 
using ICSharpCode.SharpZipLib.Core;
Line 195: Line 195:
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>
==Uso dei metodi della Classe Helper==
+
===Uso dei metodi della Classe Helper===
 
<syntaxhighlight lang="csharp">
 
<syntaxhighlight lang="csharp">
 
// Da un esempio reale
 
// Da un esempio reale

Latest revision as of 18:41, 29 October 2024

Sharp Zip

La libreria è installabile mediante NuGet, quella che attualmente (29/10/2024) ho usato è la "SharpZipLib.NetStandard" by ICSharpCode ver 1.07 pubblicata il 24 ottobre 2017. Nella classe dove verrà usata occorrono due using:

using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;

Esempio

Nella Classe Helper

using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
 
namespace CommonLib
{
    public static class CommonHlp
    {
        #region ZIP
        /// <summary>
        /// /// Zippa in un file i files indicati in CSV. Se fornita una password la applica. 
        /// La cartella di destinazione se non c'è verrà creata e l'eventuale precedente file archivio verrà prima cancellato.
        /// </summary>
        /// <param name="srcFolder">Cartella contenente i files da comprimere in uno zip file</param>
        /// <param name="destFullPath">Path completo di nome del file ZIP. Indica la cartella temporanea dove verà creato il file zip</param>
        /// <param name="srcFileListCSV">Nomi di files da selezionare, CSV con separatore ',' SENZA SPAZI.</param>
        /// <param name="password"></param>
        /// <param name="strMessageOut">Variabile in uscita contenente le info di log</param>
        /// <param name="compressionLevel">Livello di compressione da 0(assembla solo i file) a 9(migliore compressione)</param>
        /// <param name="deleteAfterZip">Se cancellare il file compresso appena dopo l'elaborazione</param>
        /// <returns></returns>
        public static string ZipFiles(string srcFolder, string destFullPath
                                    , string srcFileListCSV
                                    , string password
                                    , ref string strMessageOut
                                    , int compressionLevel = 4
                                    , bool deleteAfterZip = false)
        {
            string outErrorMessage = string.Empty;
            int nrFilesSelected = 0;
            try
            {
                #region Verifiche
                if (string.IsNullOrWhiteSpace(destFullPath))
                {
                    throw new Exception("Please set full path zip file destination folder.");
                }
                if (string.IsNullOrWhiteSpace(srcFolder))
                {
                    throw new Exception("Please supply the folder to zip.");
                }
                #endregion
 
                if (!string.IsNullOrEmpty(srcFileListCSV))
                {
                    srcFileListCSV = "," + srcFileListCSV + ",";
                }
                string destinationPath = Path.GetDirectoryName(destFullPath);
 
                #region Preliminari
                if (!Directory.Exists(destinationPath))
                {
                    Directory.CreateDirectory(destinationPath);
                    strMessageOut += string.Format("Created output zipFile directory: '{0}'.\r\n"
                                              , destinationPath);
                }
                else
                {
                    if (File.Exists(destFullPath))
                    {
                        File.Delete(destFullPath);
                        strMessageOut += string.Format("Cleaned previous zip file.\r\n");
                    }
                }
                #endregion
 
                string[] fileNames = Directory.GetFiles(srcFolder);
                using (ZipOutputStream outStream = new ZipOutputStream(File.Create(destFullPath)))
                {
                    if (!string.IsNullOrWhiteSpace(password))
                    {
                        outStream.Password = password;
                        strMessageOut += string.Format("Applying password to zip file.\r\n");
                    }
                    outStream.SetLevel(compressionLevel);
 
                    byte[] buffer = new byte[4096];
                    foreach (string fileToCompress in fileNames)
                    {
                        if (string.IsNullOrEmpty(srcFileListCSV)
                            || srcFileListCSV.IndexOf("," + Path.GetFileName(fileToCompress) + ",") >= 0)
                        {
                            // Using GetFileName makes the result compatible with XP
                            // as the resulting path is not absolute.
                            ZipEntry entry = new ZipEntry(Path.GetFileName(fileToCompress));
                            // Could also use the last write time or similar for the file.
                            entry.DateTime = DateTime.Now;
                            outStream.PutNextEntry(entry);
 
                            using (FileStream fs = File.OpenRead(fileToCompress))
                            {
                                // Using a fixed size buffer here makes no noticeable difference for output
                                // but keeps a lid on memory usage.
                                int sourceBytes;
                                do
                                {
                                    sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                    outStream.Write(buffer, 0, sourceBytes);
                                } while (sourceBytes > 0);
                            }
                            nrFilesSelected++;
                            if (!string.IsNullOrWhiteSpace(srcFileListCSV))
                            {
                                strMessageOut += string.Format("{0} files added to zip archive.\r\n"
                                                      , nrFilesSelected);
                            }
                        }
                        if (deleteAfterZip)
                        {
                            File.Delete(fileToCompress);
                        }
                    }
                    outStream.Finish(); // Ensure trailing information for a Zip file is appended. 
                    outStream.Close();  // Close is important to wrap things up and unlock the file.
                }
                strMessageOut += string.Format("Created protected zipFile: '{0}'.\r\n"
                                            , destFullPath);
            }
            catch (Exception)
            {
                throw;
            }
            return outErrorMessage;
        }
 
        public static string UnZipFile(string srcFileFullPath, string destPath
                                     , string password, ref string strMessageOut
                                     , bool deleteAfterUnZip = false)
        {
            string outErrorMessage = string.Empty;
            string tmpMessage = string.Empty;
            int nrFilesExtracted = 0;
            try
            {
                FileStream fs = File.OpenRead(srcFileFullPath);
                using (ZipFile zip = new ZipFile(fs))
                {
                    if (!string.IsNullOrEmpty(password))
                    {
                        zip.Password = password;
                        tmpMessage = "with password";
                    }
                    foreach (ZipEntry ze in zip)
                    {
                        // Ignore directories
                        if (!ze.IsFile)
                        {                            
                            continue; 
                        }
                        string entryFileName = ze.Name;
                        byte[] buffer = new byte[4096]; // 4K
                        Stream zipStream = zip.GetInputStream(ze);
                        string fullZipToPath = Path.Combine(destPath, entryFileName);
                        using (FileStream streamWriter = File.Create(fullZipToPath))
                        {
                            StreamUtils.Copy(zipStream, streamWriter, buffer);
                        }
                        nrFilesExtracted++;
                    }
                    zip.IsStreamOwner = true;   // Makes close also shut the underlying stream
                    zip.Close();                // Ensure we release resources
                }                
                strMessageOut += string.Format("UnZip {0} {1} files."
                                            , tmpMessage, nrFilesExtracted);
                if (deleteAfterUnZip)
                {
                    File.Delete(srcFileFullPath);
                }
            }
            catch (Exception ex)
            {
                outErrorMessage = string.Format("[UnZipFile] After {0} file: {1}"
                                                , nrFilesExtracted, ex.Message);
                throw new Exception(outErrorMessage);
            }
            return outErrorMessage;
        }
        #endregion
	}
}

Uso dei metodi della Classe Helper

// Da un esempio reale
 
// Zip di files:
CommonHlp.ZipFiles(SharedSetupPar.SetupCfg.ArchiveDocPathTmp
                  , docFileNameFullPath, string.Empty, password
                  , ref strMessageOut, compressionLevel);
// UnZip
CommonHlp.UnZipFile(srcZipFileFullPath, SharedSetupPar.SetupCfg.ArchiveDocPathTmp
                    , password, ref strMessageOut);

Mappa e Link


C# | Librerie di terze parti PlugIn


Visual Studio | MS SQL | Dizionario


Parole chiave: