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 / Exemple :
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")
Vous n'êtes pas encore membre ?
inscrivez-vous, c'est gratuit et ça prend moins d'une minute !
Les membres obtiennent plus de réponses que les utilisateurs anonymes.
Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.
Le fait d'être membre vous permet d'avoir des options supplémentaires.