Accueil > > > CLASSE PERMETTANT DE ZIPPER DE(S) FICHIER(S) AVEC (OU SANS) LEUR ARBORESCENCE
CLASSE PERMETTANT DE ZIPPER DE(S) FICHIER(S) AVEC (OU SANS) LEUR ARBORESCENCE
Information sur la source
Description
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")
Historique
- 15 octobre 2007 09:56:48 :
- update
- 15 octobre 2007 10:28:18 :
- Update suivant commentaires
Sources de la même categorie
Commentaires et avis
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ème : Je désire ré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 à la recherche d'une bon libraire pour décompresser des fichiers sous pocketpc, j'ai tenté 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
|
Derniers Blogs
UNE JOLIE-HORLOGE ET PAS QU'UN PEU !UNE JOLIE-HORLOGE ET PAS QU'UN PEU ! par neodante
Pour les possesseurs d'iPhone, ça y est Bijin Tokei - qui se traduit littéralement en Français par " Jolie Horloge " - est arrivé et GRATUITEMENT s'il vous plaît ! Après la version Tokyo, Hokkaido, night club, racing, Gal, "pour les mademoiselles'", . voi...
Cliquez pour lire la suite de l'article par neodante TECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICESTECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICES par ROMELARD Fabrice
Animé par: Gaetan Bouveret et Julien Chomarat Business Connectivity Services (BCS) est dans SharePoint 2010 la version 2 de Business Data Catalog (BDC dans SharePoint 2007). Il s'agit de la solution permettant de visualiser des données provenan...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice [DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE[DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE par orion
Comme de nombreux geek, je suis un grand amateur de série TV et je rate régulièrement des épisodes de mes séries préférés. Une solution s'offre à vous avec ce merveilleux site : Tv Gorge - www.tvgorge.com Moteur de recherche à l'appui, vous pouvez ...
Cliquez pour lire la suite de l'article par orion TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010 par ROMELARD Fabrice
Animé par: Vincent Bellet et Baptiste Giraudier La BI dans SharePoint 2010, Les nouveaux services d'application dans SP2010 et SQL Server Reporting services 2008 R2. La BI dans SharePoint est généralisée pour tous afin de permettre à tous les coll...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Logiciels
DB-MAIN (9.1.0)DB-MAIN (9.1.0)DB-MAIN is a data-modeling and data-architecture tool. It is designed to help developers and anal... Cliquez pour télécharger DB-MAIN Xilisoft DPG Convertisseur (5.1.37.0120)XILISOFT DPG CONVERTISSEUR (5.1.37.0120)Xilisoft DPG Convertisseur offre aux fans de Nintendo DS une bonne solution leur permettant de dé... Cliquez pour télécharger Xilisoft DPG Convertisseur GraphicsGale (2.01.01)GRAPHICSGALE (2.01.01)GraphicsGale est un logiciel de PixelArt avec de nombreuse fonctionnalités permettant de réalisé ... Cliquez pour télécharger GraphicsGale Architecte 3D (Platinum 2010)ARCHITECTE 3D (PLATINUM 2010)Architecte 3D Platinium vous permet de concevoir facilement les plans votre future maison, de l'é... Cliquez pour télécharger Architecte 3D TeamViewer 5 (TeamViewer 5)TEAMVIEWER 5 (TEAMVIEWER 5)Dépanner un ami,expliquer une manipulation devient un jeu d'enfant.
Prise en main d'un autre ord... Cliquez pour télécharger TeamViewer 5
|