Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum. Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !

CLASSE PERMETTANT DE ZIPPER DE(S) FICHIER(S) AVEC (OU SANS) LEUR ARBORESCENCE


Information sur la source

Catégorie :.NET Source .NET ( DotNet ) Classé sous : zip, ICSharpCode, arborescence Niveau : Débutant Date de création : 15/10/2007 Date de mise à jour : 15/10/2007 10:28:18 Vu / téléchargé: 3 552 / 167

Note :
Aucune note

Commentaire sur cette source (7)
Ajouter un commentaire et/ou une note

Description

Cliquez pour voir la capture en taille normale
Le path de chaque fichier est stocké dans un ArrayList.
Le zippage s'effectue en fonction du level de compression et peut incorporer l'arborescence du ou des fichier(s).
Ce code source est basé sur la librairie ICSharpCode qui devrait etre compatible avec un bon nombre de framework.
 

Source

  • using System;
  • using System.Data;
  • using System.Configuration;
  • using System.Collections;
  • using System.Web;
  • using System.Web.Security;
  • using System.Web.UI;
  • using System.Web.UI.WebControls;
  • using System.Web.UI.WebControls.WebParts;
  • using System.Web.UI.HtmlControls;
  • using ICSharpCode.SharpZipLib.Zip;
  • using System.IO;
  • using System.Xml;
  • using System.Data.OleDb;
  • using System.Windows.Forms;
  • public class clsZipFile
  • {
  • //Declaration of classwide variables
  • public string c_sZipPath = "C:\\Test\\ZipedFiles\\Output.zip"; //By default the output zip file is stocked here
  • public ArrayList c_alFiles = new ArrayList(); //Contains the list of the paths of each files to be zipped
  • public ZipOutputStream c_zosZip; //Zip Stream (see ICSharpCode.SharpZipLib)
  • public int c_iPosDebCheminRacine; //Position of the begining of the path
  • public string sMessage;
  • /************************************
  • * Old function kept but not used *
  • * for reading a XML File *
  • * **********************************/
  • public bool ReadXMLFile()
  • {
  • bool bRetValue;
  • //The path of the XML file is written directly in the code
  • XmlDataDocument document = new XmlDataDocument();
  • document.Load("D:\\MY_DOCUMENTS\\Visual Studio 2005\\WebSites\\WebZip\\XMLFile.xml");
  • // In this XML File an 'adress' tag is set to find the path of each file
  • XmlNodeList elementsByTagName = document.GetElementsByTagName("adress");
  • try
  • {
  • //Loop to store each file path into the ArrayList
  • foreach (XmlNode node in elementsByTagName)
  • {
  • c_alFiles.Add(string.Format(node.FirstChild.Value));
  • }
  • }
  • finally
  • {
  • bRetValue=true;
  • }
  • return bRetValue;
  • }
  • /************************************************************
  • * Zip a Tree *
  • * *
  • * Input: bool to tell whether or not zipping the tree *
  • * *
  • * Output: bool result of treatment *
  • * **********************************************************/
  • private bool BZipTree(bool bWithTree)
  • {
  • //Loop to zip each files
  • foreach (string sCurrentFilePath in this.c_alFiles)
  • {
  • string fullPath = Path.GetFullPath(sCurrentFilePath); //Get the full path
  • string fileName = Path.GetFileName(sCurrentFilePath); //Get the name of the file
  • //Zip the current file end return the bool value
  • if (!this.BZipFile(fullPath, fileName, bWithTree))
  • {
  • return false;
  • }
  • }
  • return true;
  • }
  • /********************************************
  • * Zip a File *
  • * *
  • * Input: string File Path *
  • * string Name of the File *
  • * *
  • * Output: Boolean Result of the process *
  • ********************************************/
  • public bool BZipFile(string sFilePath, string sFileName, bool bWithTree)
  • {
  • bool flag;
  • //Loop while the flag isn't true: until the file has been zipped correctly
  • do
  • {
  • flag = false;
  • FileStream fsFile = null;
  • long lFileSize = 0;
  • try
  • {
  • ZipEntry entry;
  • string sDirPath = this.SGetDirPath(sFilePath);
  • string sRelativePath = sDirPath.Substring(this.c_iPosDebCheminRacine) + @"\" + sFileName;
  • //Get the information of the file
  • FileInfo info = new FileInfo(sFilePath);
  • lFileSize = info.Length;
  • fsFile = File.OpenRead(sFilePath);
  • //Zip the tree or not, depending on the chkbxTree status
  • if (bWithTree)
  • {
  • entry = new ZipEntry(sRelativePath);
  • }
  • else
  • {
  • entry = new ZipEntry(Path.GetFileName(sRelativePath));
  • }
  • //Set the information to the zipped file
  • entry.DateTime = info.LastWriteTime;
  • entry.ExternalFileAttributes = (int)info.Attributes;
  • entry.Size = info.Length;
  • // zipping the file
  • this.c_zosZip.PutNextEntry(entry);
  • byte[] array = new byte[0x1000];
  • long num2 = 0L;
  • while (true)
  • {
  • int count = fsFile.Read(array, 0, 0x1000);
  • if (count < 1)
  • {
  • break;
  • }
  • this.c_zosZip.Write(array, 0, count);
  • num2 += count;
  • }
  • }
  • // Exception treatment
  • catch (Exception ex)
  • {
  • string sMsg = "Function: bZipFile()";
  • string sMsgError = "";
  • if (ex.Message != "")
  • {
  • sMsgError = ex.Message.Trim();
  • if (ex.InnerException != null)
  • {
  • sMsgError += "\r\n" + ex.InnerException.Message;
  • }
  • }
  • sMessage = sMsg + "\n" + sMsgError;
  • }
  • //Close the zipped file
  • finally
  • {
  • if (fsFile == null)
  • {
  • fsFile.Close();
  • }
  • }
  • }
  • while (flag);
  • return true;
  • }
  • /********************************************
  • * Get the directory path *
  • * *
  • * Input: string path of the file *
  • * *
  • * Output: string Path of the directory *
  • * ******************************************/
  • public string SGetDirPath(string sCheminFichier)
  • {
  • //Take off the final slash
  • return this.STakeOffFinalSlash(Path.GetDirectoryName(sCheminFichier));
  • }
  • /********************************************
  • * Set a path without final slash *
  • * *
  • * Input: string path *
  • * *
  • * Output: string Path without final slash *
  • * ******************************************/
  • private string STakeOffFinalSlash(string sPath)
  • {
  • int length = sPath.Length; //Get the length of the path
  • if (length == 0)
  • {
  • return "";
  • }
  • length--;
  • if (sPath.Substring(length) == @"\") //Check if the last char is \
  • {
  • return sPath.Substring(0, length);
  • }
  • return sPath;
  • }
  • /****************************************
  • * Verify existance of the output path *
  • * *
  • * Input: string of the output path *
  • * *
  • * Output: boolean result of process *
  • ****************************************/
  • private bool BVerifyOutputPath(string sOutputPath)
  • {
  • string sDirOutputPath = Path.GetDirectoryName(sOutputPath); //Get the directory path
  • //Creation of the output directory if it does not exist
  • if (!Directory.Exists(sDirOutputPath))
  • {
  • Directory.CreateDirectory(sDirOutputPath);
  • }
  • return true;
  • }
  • /****************************************
  • * Start zipping process *
  • * *
  • * Input: - *
  • * *
  • * Output: boolean result of process *
  • * **************************************/
  • public bool BStartZipTree(bool bWithTree, int iLvlCompression)
  • {
  • FileStream baseOutputStream = null;
  • try
  • {
  • BVerifyOutputPath(this.c_sZipPath); //Verification of the existance of the directory
  • baseOutputStream = File.Create(this.c_sZipPath); //Creation of the zipped file
  • this.c_zosZip = new ZipOutputStream(baseOutputStream);
  • this.c_zosZip.SetLevel(iLvlCompression);
  • ZipConstants.DefaultCodePage = 850;
  • if (!this.BZipTree(bWithTree))
  • {
  • return false;
  • }
  • }
  • //Treatment of the exception
  • catch (Exception ex)
  • {
  • string sMsg = "Function: bStartZipTree()";
  • string sMsgError = "";
  • if (ex.Message != "")
  • {
  • sMsgError = ex.Message.Trim();
  • if (ex.InnerException != null)
  • {
  • sMsgError += "\r\n" + ex.InnerException.Message;
  • }
  • }
  • sMessage = sMsg + "\n" + sMsgError;
  • }
  • //Finish and close the zipped file
  • finally
  • {
  • if (this.c_zosZip != null)
  • {
  • try
  • {
  • this.c_zosZip.Finish();
  • this.c_zosZip.Close();
  • }
  • catch (Exception ex)
  • {
  • string sMsg = "Function: bStartZipTree()";
  • string sMsgError = "";
  • if (ex.Message != "")
  • {
  • sMsgError = ex.Message.Trim();
  • if (ex.InnerException != null)
  • {
  • sMsgError += "\r\n" + ex.InnerException.Message;
  • }
  • }
  • sMessage = sMsg + "\n" + sMsgError;
  • }
  • }
  • //Close the outputstream if it's null
  • if (baseOutputStream == null)
  • {
  • baseOutputStream.Close();
  • }
  • //Free zip element
  • this.c_zosZip = null;
  • }
  • return true;
  • }
  • }
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using ICSharpCode.SharpZipLib.Zip;
using System.IO;
using System.Xml;
using System.Data.OleDb;
using System.Windows.Forms;

public class clsZipFile
{
    //Declaration of classwide variables
    public string c_sZipPath = "C:\\Test\\ZipedFiles\\Output.zip";      //By default the output zip file is stocked here
    public ArrayList c_alFiles = new ArrayList();                       //Contains the list of the paths of each files to be zipped
    public ZipOutputStream c_zosZip;                                    //Zip Stream (see ICSharpCode.SharpZipLib)
    public int c_iPosDebCheminRacine;                                   //Position of the begining of the path
    public string sMessage;

    /************************************
     *  Old function kept but not used  *
     *  for reading a XML File          *
     * **********************************/
    public bool ReadXMLFile()
    {
        bool bRetValue;
        //The path of the XML file is written directly in the code
        XmlDataDocument document = new XmlDataDocument();
        document.Load("D:\\MY_DOCUMENTS\\Visual Studio 2005\\WebSites\\WebZip\\XMLFile.xml");

        // In this XML File an 'adress' tag is set to find the path of each file
        XmlNodeList elementsByTagName = document.GetElementsByTagName("adress");
        try
        {
            //Loop to store each file path into the ArrayList
            foreach (XmlNode node in elementsByTagName)
            {
                c_alFiles.Add(string.Format(node.FirstChild.Value));
            }
        }
        finally
        {
            bRetValue=true;
        }
        return bRetValue;
    }

    /************************************************************
     *      Zip a Tree                                          *
     *                                                          *
     *  Input:  bool to tell whether or not zipping the tree    *
     *                                                          *
     *  Output: bool result of treatment                        *
     * **********************************************************/
    private bool BZipTree(bool bWithTree)
    {
        //Loop to zip each files
        foreach (string sCurrentFilePath in this.c_alFiles)
        {
            string fullPath = Path.GetFullPath(sCurrentFilePath);   //Get the full path
            string fileName = Path.GetFileName(sCurrentFilePath);   //Get the name of the file

            //Zip the current file end return the bool value
            if (!this.BZipFile(fullPath, fileName, bWithTree))
            {
                return false;
            }
        }
        return true;
    }

    /********************************************
     *      Zip a File                          *
     *                                          *
     *  Input:  string File Path                *
     *          string Name of the File         *
     *                                          *
     *  Output: Boolean Result of the process   *
     ********************************************/
    public bool BZipFile(string sFilePath, string sFileName, bool bWithTree)
    {
        bool flag;
        //Loop while the flag isn't true: until the file has been zipped correctly
        do
        {
            flag = false;
            FileStream fsFile = null;
            long lFileSize = 0;
            try
            {
                ZipEntry entry;
                string sDirPath = this.SGetDirPath(sFilePath);
                string sRelativePath = sDirPath.Substring(this.c_iPosDebCheminRacine) + @"\" + sFileName;

                //Get the information of the file
                FileInfo info = new FileInfo(sFilePath);
                lFileSize = info.Length;
                fsFile = File.OpenRead(sFilePath);

                //Zip the tree or not, depending on the chkbxTree status
                if (bWithTree)
                {
                    entry = new ZipEntry(sRelativePath);
                }
                else
                {
                    entry = new ZipEntry(Path.GetFileName(sRelativePath));
                }

                //Set the information to the zipped file
                entry.DateTime = info.LastWriteTime;
                entry.ExternalFileAttributes = (int)info.Attributes;
                entry.Size = info.Length;

                // zipping the file
                this.c_zosZip.PutNextEntry(entry);
                byte[] array = new byte[0x1000];
                long num2 = 0L;
                while (true)
                {
                    int count = fsFile.Read(array, 0, 0x1000);
                    if (count < 1)
                    {
                        break;
                    }
                    this.c_zosZip.Write(array, 0, count);
                    num2 += count;
                }
            }

            // Exception treatment
            catch (Exception ex)
            {
                string sMsg = "Function: bZipFile()";
                string sMsgError = "";
                if (ex.Message != "")
                {
                    sMsgError = ex.Message.Trim();
                    if (ex.InnerException != null)
                    {
                        sMsgError += "\r\n" + ex.InnerException.Message;
                    }
                }
                sMessage = sMsg + "\n" + sMsgError;

            }

            //Close the zipped file
            finally
            {
                if (fsFile == null)
                {
                    fsFile.Close();
                }
            }
        }
        while (flag);
        return true;
    }

    /********************************************
     *  Get the directory path                  *
     *                                          *
     *  Input:  string path of the file         *
     *                                          *
     *  Output: string Path of the directory    *
     * ******************************************/
    public string SGetDirPath(string sCheminFichier)
    {
        //Take off the final slash
        return this.STakeOffFinalSlash(Path.GetDirectoryName(sCheminFichier));
    }

    /********************************************
     *  Set a path without final slash          *
     *                                          *
     *  Input:  string path                     *
     *                                          *
     *  Output: string Path without final slash *
     * ******************************************/
    private string STakeOffFinalSlash(string sPath)
    {
        int length = sPath.Length;                        //Get the length of the path
        if (length == 0)
        {
            return "";
        }
        length--;
        if (sPath.Substring(length) == @"\")              //Check if the last char is \
        {
            return sPath.Substring(0, length);
        }
        return sPath;
    }

    /****************************************
     *  Verify existance of the output path *
     *                                      *
     *  Input:  string of the output path   *
     *                                      *
     *  Output: boolean result of process   *
     ****************************************/
    private bool BVerifyOutputPath(string sOutputPath)
    {
        string sDirOutputPath = Path.GetDirectoryName(sOutputPath);     //Get the directory path

        //Creation of the output directory if it does not exist
        if (!Directory.Exists(sDirOutputPath))
        {
            Directory.CreateDirectory(sDirOutputPath);
        }
        return true;
    }

    /****************************************
     *  Start zipping process               *
     *                                      *
     *  Input:  -                           *
     *                                      *
     *  Output: boolean result of process   *
     * **************************************/
    public bool BStartZipTree(bool bWithTree, int iLvlCompression)
    {
        FileStream baseOutputStream = null;
        try
        {
            BVerifyOutputPath(this.c_sZipPath);                             //Verification of the existance of the directory
            baseOutputStream = File.Create(this.c_sZipPath);                //Creation of the zipped file
            this.c_zosZip = new ZipOutputStream(baseOutputStream);
            this.c_zosZip.SetLevel(iLvlCompression);
            ZipConstants.DefaultCodePage = 850;
            if (!this.BZipTree(bWithTree))
            {
                return false;
            }
        }

        //Treatment of the exception
        catch (Exception ex)
        {
            string sMsg = "Function: bStartZipTree()";
            string sMsgError = "";
            if (ex.Message != "")
            {
                sMsgError = ex.Message.Trim();
                if (ex.InnerException != null)
                {
                    sMsgError += "\r\n" + ex.InnerException.Message;
                }
            }
            sMessage = sMsg + "\n" + sMsgError;
        }

        //Finish and close the zipped file
        finally
        {
            if (this.c_zosZip != null)
            {
                try
                {
                    this.c_zosZip.Finish();
                    this.c_zosZip.Close();
                }
                catch (Exception ex)
                {
                    string sMsg = "Function: bStartZipTree()";
                    string sMsgError = "";
                    if (ex.Message != "")
                    {
                        sMsgError = ex.Message.Trim();
                        if (ex.InnerException != null)
                        {
                            sMsgError += "\r\n" + ex.InnerException.Message;
                        }
                    }
                    sMessage = sMsg + "\n" + sMsgError;
                }
            }

            //Close the outputstream if it's null
            if (baseOutputStream == null)
            {
                baseOutputStream.Close();
            }

            //Free zip element
            this.c_zosZip = null;
        }
        return true;
    }
}

Conclusion

Je veux pas la jouer petit bras, mais comme c'est ma premiere source, j'espere que vos critiques ne seront pas trop acerbes.
Cela dit, je prendrai tout ce que vous me donnerai. ^^
J'ai laisse dans le zip un exemple complet d'utilisation. (le zip de sortie est directement placé dans un répertoire et un nom par defaut: "C:\Test\ZipedFiles\Output.zip")
 

Fichier Zip

Pour les "Membres Club", vous pouvez télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !

Télécharger le zip

Historique

15 octobre 2007 09:56:48 :
update
15 octobre 2007 10:28:18 :
Update suivant commentaires

Commentaires et avis

signaler à un administrateur
Commentaire de sebmafate le 15/10/2007 10:10:14 administrateur CS

Juste quelques remarques rapides sur ton code...
- Pourquoi n'utilises-tu pas les commentaires XML pour tes méthodes ?
- En .net on utilise la syntaxe Camel : toutes les méthodes et les propriétés doivent avoir une majuscule

une erreur ici : (ligne 287)
            //Close the outputstream if it's null
            if (baseOutputStream == null)
            {
                baseOutputStream.Close();
            }

si baseOuputStream est nul alors l'appel de la méthode Close() soulèvera une exception.

c'est juste une lecture en diagonale.

signaler à un administrateur
Commentaire de Mitch Buchannon le 15/10/2007 10:29:28

Merci pour les remarques!
Je prends note des commentaires XML.

signaler à un administrateur
Commentaire de Bidou le 15/10/2007 11:52:06 administrateur CS

Après avoir passé en revue en 2min, j'ajouterais:

- Pourquoi les variables de classes sont publiques ?????
- public ArrayList c_alFiles = new ArrayList(); // Ca c'est du framework 1, voire les Generics
- (this.c_iPosDebCheminRacine) + @"\" + sFileName; // Voire la class Path pour concaténer des path
- String.Format jamais utilisé ???
- Even. utiliser un using pour les FileStream...

Rien d'autre au premier coup d'oeil.

signaler à un administrateur
Commentaire de Lutinore le 15/10/2007 15:37:32 administrateur CS

Les méthodes BZipFile et BVerifyOutputPath renvoient toujours "true".

signaler à un administrateur
Commentaire de sebmafate le 15/10/2007 15:44:40 administrateur CS

true ou... exception ;)

signaler à un administrateur
Commentaire de Lutinore le 16/10/2007 00:11:23 administrateur CS

Peu importe qu'elles lancent des exceptions ou pas.. elles ne renverront jamais "false", la valeur de retour est donc inutile, elles devraient être marquées "void".

signaler à un administrateur
Commentaire de econs le 20/10/2007 08:30:07 administrateur CS

J'ai comme l'impression que le Do de BZipFile ne sert à rien. On en sort si 'flag' est false, mais comme il n'est jamais mis à true, et bien on sort directement après le premier passage.

Ajouter un commentaire

Discussions en rapport avec ce code source dans le forum

datagrid [ par mapo62 ] bonjour,Quand on crée une arborescence dans un DataGrid, est il possible de dérouler l'arobrescence automatiquement dès le remplissage de la grille sa Compression / Décompression Zip avec SharpZipLib ? [ par floorfi ] Bonsoir !Voilà, je voudrais savoir si qq1 avait un tuto (en fr de préférence) ou un source concernant l'utilisation de la lib SharpZipLib pour C#.En f acquittement serveur ftp [ par dude666 ] Bonjour à tous. Voila, je suis entrain de créer une application de backup. En gros, je backup ma base de données sur mon serveur de base de données, Supprimer des fichier test*.zip(par ex) [ par yanis7518 ] Bonjour je suis debutant en Csharp et je voudrai savoir s'il etait possible de supprimer ou de copier des fichier mais en fonction du debut de leur no FTP - TreeView et ListView [ par Neo020585 ] Bonjour tout le monde^^ Je vous explique mon probl&#232;me : Je d&#233;sire r&#233;aliser un client FTP en C#. J'utilise la librairie gratuite edtFt Décompression fichier ZIP sous PocketPC 2003 en c# [ par jfmador ] Bonjour je suis &#224; la recherche d'une bon libraire pour d&#233;compresser des fichiers sous pocketpc, j'ai tent&#233; d'utiliser celle de Componen ajout d'un fichier dans un zip [ par tracks62 ] Bonjour,Est-ce qu'il est possible d'ajouter un fichier a un zip (déjà créé) avec la librairie SharpZipLib ?Dans le cas ou ce n'est pas possible, comme Representation d'une arborescence [ par Seth77 ] Salutque conseillez vous pour la representation d'une arborescence dans une BD ...J'ai trouve la soluce de la representation intervallaire, avez vous compression zip targzip [ par dacor ] bonjour,je voudrais écrire une fonction qui permetrait de comprésser des fichiers en zip targzip.est ce qu'il éxiste une bibliothèque pour écrire ce g CS TOOLBAR [ par BruNews ] OHE les utilisateurs IE: NOUVELLE CSBar incluant liens vers tous les sites CS, Emploi, Technos, boutique et geoguide y compris. http://brunew


Nos sponsors

Sondage...

CalendriCode

Juillet 2009
LMMJVSD
  12345
6789101112
13141516171819
20212223242526
2728293031  

Consulter la suite du CalendriCode

Téléchargements

Logiciels à télécharger sur le même thème :

Comparez les prix Nouvelle version

Photothèque Nouveau !



Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés
Temps d'éxécution de la page : 0,889 sec

Google Coop CodeS-SourceS Google Coop CodeS-SourceS


Certaines images présentes sur le site (notament certains avatars) sont issues des collections IconShock, donc si vous souhaitez utiliser ces icons vous devez les acheter, ne les copiez pas et ne utilisez pas dans vos sites et applications sans les avoir commandé.