研究了一下,如何把文件打包成Zip文件。
下面是我经历的进程:
1. 首先看到了微软本身的打包代码,是通过System.IO.Packaging 命令空间来进行打包,你可以点击以上的链接来查看其如何打包!其主要利用PackUriHelper.CreatePartUri来对文件
// -------------------------- CreatePackage -------------------------- /// <summary> /// Creates a package zip file containing specified /// content and resource files.</summary> private static void CreatePackage() { // Convert system path and file names to Part URIs. In this example // Uri partUriDocument /* /Content/Document.xml */ = // PackUriHelper.CreatePartUri( // new Uri("Content\Document.xml", UriKind.Relative)); // Uri partUriResource /* /Resources/Image1.jpg */ = // PackUriHelper.CreatePartUri( // new Uri("Resources\Image1.jpg", UriKind.Relative)); Uri partUriDocument = PackUriHelper.CreatePartUri( new Uri(documentPath, UriKind.Relative)); Uri partUriResource = PackUriHelper.CreatePartUri( new Uri(resourcePath, UriKind.Relative)); // Create the Package // (If the package file already exists, FileMode.Create will // automatically delete it first before creating a new one. // The 'using' statement insures that 'package' is // closed and disposed when it goes out of scope.) using (Package package = Package.Open(packagePath, FileMode.Create)) { // Add the Document part to the Package PackagePart packagePartDocument = package.CreatePart(partUriDocument, System.Net.Mime.MediaTypeNames.Text.Xml); // Copy the data to the Document Part using (FileStream fileStream = new FileStream( documentPath, FileMode.Open, FileAccess.Read)) { CopyStream(fileStream, packagePartDocument.GetStream()); }// end:using(fileStream) - Close and dispose fileStream. // Add a Package Relationship to the Document Part package.CreateRelationship(packagePartDocument.Uri, TargetMode.Internal, PackageRelationshipType); // Add a Resource Part to the Package PackagePart packagePartResource = package.CreatePart(partUriResource, System.Net.Mime.MediaTypeNames.Image.Jpeg); // Copy the data to the Resource Part using (FileStream fileStream = new FileStream( resourcePath, FileMode.Open, FileAccess.Read)) { CopyStream(fileStream, packagePartResource.GetStream()); }// end:using(fileStream) - Close and dispose fileStream. // Add Relationship from the Document part to the Resource part packagePartDocument.CreateRelationship( new Uri(@"../resources/image1.jpg", UriKind.Relative), TargetMode.Internal, ResourceRelationshipType); }// end:using (Package package) - Close and dispose package. }// end:CreatePackage() // --------------------------- CopyStream --------------------------- /// <summary> /// Copies data from a source stream to a target stream.</summary> /// <param name="source"> /// The source stream to copy from.</param> /// <param name="target"> /// The destination stream to copy to.</param> private static void CopyStream(Stream source, Stream target) { const int bufSize = 0x1000; byte[] buf = new byte[bufSize]; int bytesRead = 0; while ((bytesRead = source.Read(buf, 0, bufSize)) > 0) target.Write(buf, 0, bytesRead); }// end:CopyStream()
其打包的文件打包后会有一个Relationship,还有一些额外的关联文件(想除掉,但不知怎么删除掉),如.rels文件夹和.rels.xml文件,我很不喜欢,所以也没有时间花更多的时间去三研究对文件夹进行打包。
在你看Microsoft 的实例 中,打包过程还需要知道打包的文件的ContentType,这个可以通过以下代码来解决!
private string GetContentType(string fileName) { string contentType = "application/octetstream"; string ext = System.IO.Path.GetExtension(fileName).ToLower(); Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext); if (registryKey != null && registryKey.GetValue("Content Type") != null) contentType = registryKey.GetValue("Content Type").ToString(); return contentType; }
你可以通过点击以上链接来查看如何打包压缩及解压缩
2. 网上查找的,通过Utilities命令空间来守成的,其主要用到两个类
ZipFile.cs
#region Usings using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO.Packaging; using System.IO; using System.Web; using Microsoft.Build.Utilities; #endregion namespace Utilities.FileFormats.Zip { /// <summary> /// /// Helper class for dealing with zip files /// /// </summary> public class ZipFile : IDisposable { #region Constructor /// <summary> /// /// Constructo /// </summary> /// <param name="FilePath">Path to the zip file</param> /// /// <param name="Overwrite">Should the zip file be overwritten?</param> public ZipFile(string FilePath, bool Overwrite) { if (string.IsNullOrEmpty(FilePath)) throw new ArgumentNullException("FilePath"); ZipFileStream = new FileStream(FilePath, Overwrite ? FileMode.Create : FileMode.OpenOrCreate); } #endregion #region Properties /// <summary> /// /// Zip file's FileStream /// /// </summary> protected virtual FileStream ZipFileStream { get; set; } #endregion #region Functions /// <summary> /// Adds a folder to the zip file /// /// </summary> /// /// <param name="Folder">Folder to add</param> public virtual void AddFolder(string Folder) { if (string.IsNullOrEmpty(Folder)) throw new ArgumentNullException("Folder"); if (Folder.EndsWith(@"\")) Folder = Folder.Remove(Folder.Length - 1); using (Package Package = ZipPackage.Open(ZipFileStream, FileMode.OpenOrCreate)) { List<FileInfo> Files = Utilities.IO.FileManager.FileList(Folder, true); foreach (FileInfo File in Files) { string FilePath = File.FullName.Replace(Folder, ""); AddFile(FilePath, File, Package); } } } /// <summary> /// Adds a file to the zip file 88: /// </summary> /// <param name="File">File to add</param> public virtual void AddFile(string File) { if (string.IsNullOrEmpty(File)) throw new ArgumentNullException("File"); if (!Utilities.IO.FileManager.FileExists(File)) throw new ArgumentException("File"); using (Package Package = ZipPackage.Open(ZipFileStream)) { AddFile(File, new FileInfo(File), Package); } } /// <summary> /// Uncompresses the zip file to the specified folder /// </summary> /// <param name="Folder">Folder to uncompress the file in</param> public virtual void UncompressFile(string Folder) { if (string.IsNullOrEmpty(Folder)) throw new ArgumentNullException(Folder); Utilities.IO.FileManager.CreateDirectory(Folder); using (Package Package = ZipPackage.Open(ZipFileStream, FileMode.Open, FileAccess.Read)) { foreach (PackageRelationship Relationship in Package.GetRelationshipsByType("http://schemas.microsoft.com/opc/2006/sample/document")) { Uri UriTarget = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), Relationship.TargetUri); PackagePart Document = Package.GetPart(UriTarget); Extract(Document, Folder); } if (File.Exists(Folder + @"\[Content_Types].xml")) File.Delete(Folder + @"\[Content_Types].xml"); } } /// <summary> /// /// Extracts an individual file /// </summary> /// <param name="Document">Document to extract</param> /// <param name="Folder">Folder to extract it into</param> protected virtual void Extract(PackagePart Document, string Folder) { if (string.IsNullOrEmpty(Folder)) throw new ArgumentNullException(Folder); string Location = Folder + System.Web.HttpUtility.UrlDecode(Document.Uri.ToString()).Replace('\\', '/'); Utilities.IO.FileManager.CreateDirectory(Path.GetDirectoryName(Location)); byte[] Data = new byte[1024]; using (FileStream FileStream = new FileStream(Location, FileMode.Create)) { Stream DocumentStream = Document.GetStream(); while (true) { int Size = DocumentStream.Read(Data, 0, 1024); FileStream.Write(Data, 0, Size); if (Size != 1024) break; } FileStream.Close(); } } /// <summary> /// /// Adds a file to the zip file /// /// </summary> /// /// <param name="File">File to add</param> /// /// <param name="FileInfo">File information</param> /// /// <param name="Package">Package to add the file to</param> protected virtual void AddFile(string File, FileInfo FileInfo, Package Package) { if (string.IsNullOrEmpty(File)) throw new ArgumentNullException("File"); if (!Utilities.IO.FileManager.FileExists(FileInfo.FullName)) throw new ArgumentException("File"); Uri UriPath = PackUriHelper.CreatePartUri(new Uri(File, UriKind.Relative)); PackagePart PackagePart = Package.CreatePart(UriPath, System.Net.Mime.MediaTypeNames.Text.Xml, CompressionOption.Maximum); byte[] Data = null; Utilities.IO.FileManager.GetFileContents(FileInfo.FullName, out Data); PackagePart.GetStream().Write(Data, 0, Data.Count()); Package.CreateRelationship(PackagePart.Uri, TargetMode.Internal, "http://schemas.microsoft.com/opc/2006/sample/document"); } #endregion #region IDisposable Members public void Dispose() { if (ZipFileStream != null) { ZipFileStream.Close(); ZipFileStream.Dispose(); ZipFileStream = null; } } #endregion } }
FileManager.cs
#region Usings using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; #endregion namespace Utilities.IO { public static class FileManager { #region Public Static Functions #region SaveFile public static void SaveFile(string Content, string FileName, bool Append = false) { FileStream Writer = null; try { byte[] ContentBytes = Encoding.UTF8.GetBytes(Content); int Index = FileName.LastIndexOf('/'); if (Index <= 0) { Index = FileName.LastIndexOf('\\'); } if (Index <= 0) { throw new Exception("Directory must be specified for the file"); } string Directory = FileName.Remove(Index) + "/"; if (!DirectoryExists(Directory)) { CreateDirectory(Directory); } bool Opened = false; while (!Opened) { try { if (Append) { Writer = File.Open(FileName, FileMode.Append, FileAccess.Write, FileShare.None); } else { Writer = File.Open(FileName, FileMode.Create, FileAccess.Write, FileShare.None); } Opened = true; } catch (System.IO.IOException) { throw; } } Writer.Write(ContentBytes, 0, ContentBytes.Length); Writer.Close(); } catch { throw; } finally { if (Writer != null) { Writer.Close(); Writer.Dispose(); } } } public static void SaveFile(string Content, string FileName, Uri FTPServer, string UserName, string Password) { Uri TempURI = new Uri(Path.Combine(FTPServer.ToString(), FileName)); FtpWebRequest FTPRequest = (FtpWebRequest)FtpWebRequest.Create(TempURI); FTPRequest.Credentials = new NetworkCredential(UserName, Password); FTPRequest.KeepAlive = false; FTPRequest.Method = WebRequestMethods.Ftp.UploadFile; FTPRequest.UseBinary = true; FTPRequest.ContentLength = Content.Length; FTPRequest.Proxy = null; using (Stream TempStream = FTPRequest.GetRequestStream()) { System.Text.ASCIIEncoding TempEncoding = new System.Text.ASCIIEncoding(); byte[] TempBytes = TempEncoding.GetBytes(Content); TempStream.Write(TempBytes, 0, TempBytes.Length); } FTPRequest.GetResponse(); } public static void SaveFile(byte[] Content, string FileName, bool Append = false) { FileStream Writer = null; try { int Index = FileName.LastIndexOf('/'); if (Index <= 0) { Index = FileName.LastIndexOf('\\'); } if (Index <= 0) { throw new Exception("Directory must be specified for the file"); } string Directory = FileName.Remove(Index) + "/"; if (!DirectoryExists(Directory)) { CreateDirectory(Directory); } bool Opened = false; while (!Opened) { try { if (Append) { Writer = File.Open(FileName, FileMode.Append, FileAccess.Write, FileShare.None); } else { Writer = File.Open(FileName, FileMode.Create, FileAccess.Write, FileShare.None); } Opened = true; } catch (System.IO.IOException) { throw; } } Writer.Write(Content, 0, Content.Length); Writer.Close(); } catch { throw; } finally { if (Writer != null) { Writer.Close(); Writer.Dispose(); } } } #endregion #region Delete public static void Delete(string FileName) { File.Delete(FileName); } #endregion #region RenameFile public static void RenameFile(string FileName, string NewFileName) { File.Move(FileName, NewFileName); } #endregion #region DirectoryExists public static bool DirectoryExists(string DirectoryPath) { return Directory.Exists(DirectoryPath); } #endregion #region FileExists public static bool FileExists(string FileName) { return File.Exists(FileName); } #endregion #region DirectoryList public static List<DirectoryInfo> DirectoryList(string DirectoryPath) { List<DirectoryInfo> Directories = new List<DirectoryInfo>(); if (DirectoryExists(DirectoryPath)) { DirectoryInfo Directory = new DirectoryInfo(DirectoryPath); DirectoryInfo[] SubDirectories = Directory.GetDirectories(); foreach (DirectoryInfo SubDirectory in SubDirectories) { Directories.Add(SubDirectory); } } return Directories; } #endregion #region CreateDirectory public static void CreateDirectory(string DirectoryPath) { Directory.CreateDirectory(DirectoryPath); } #endregion #region DeleteDirectory public static void DeleteDirectory(string DirectoryPath) { Directory.Delete(DirectoryPath, true); } #endregion #region FileList public static List<FileInfo> FileList(string DirectoryPath, bool Recursive = false) { List<FileInfo> Files = new List<FileInfo>(); if (DirectoryExists(DirectoryPath)) { DirectoryInfo Directory = new DirectoryInfo(DirectoryPath); FileInfo[] SubFiles = Directory.GetFiles(); foreach (FileInfo SubFile in SubFiles) { Files.Add(SubFile); } if (Recursive) { DirectoryInfo[] SubDirectories = Directory.GetDirectories(); foreach (DirectoryInfo SubDirectory in SubDirectories) { List<FileInfo> TempFiles = FileList(SubDirectory.FullName, true); foreach (FileInfo File in TempFiles) { Files.Add(File); } } } } return Files; } #endregion #region GetFileContents public static string GetFileContents(string FileName) { return GetFileContents(FileName, 5000); } public static string GetFileContents(string FileName, int TimeOut) { StreamReader Reader = null; int StartTime = System.Environment.TickCount; try { if (!FileExists(FileName)) return ""; bool Opened = false; while (!Opened) { try { if (System.Environment.TickCount - StartTime >= TimeOut) throw new System.IO.IOException("File opening timed out"); Reader = File.OpenText(FileName); Opened = true; } catch (System.IO.IOException) { throw; } } string Contents = Reader.ReadToEnd(); Reader.Close(); return Contents; } catch { throw; } finally { if (Reader != null) { Reader.Close(); Reader.Dispose(); } } } public static void GetFileContents(string FileName, out byte[] Output, int TimeOut) { FileStream Reader = null; int StartTime = System.Environment.TickCount; try { if (!FileExists(FileName)) { Output = null; return; } bool Opened = false; while (!Opened) { try { if (System.Environment.TickCount - StartTime >= TimeOut) throw new System.IO.IOException("File opening timed out"); Reader = File.OpenRead(FileName); Opened = true; } catch (System.IO.IOException) { throw; } } byte[] Buffer = new byte[1024]; using (MemoryStream TempReader = new MemoryStream()) { while (Reader.Read(Buffer, 0, 1024) == 1024) { TempReader.Write(Buffer, 0, Buffer.Length); } Reader.Close(); Output = TempReader.ToArray(); TempReader.Close(); } } catch { Output = null; throw; } finally { if (Reader != null) { Reader.Close(); Reader.Dispose(); } } } public static string GetFileContents(Uri FileName) { using (WebClient Client = new WebClient()) { using (StreamReader Reader = new StreamReader(Client.OpenRead(FileName))) { string Contents = Reader.ReadToEnd(); Reader.Close(); return Contents; } } } public static void GetFileContents(Uri FileName, out Stream OutputStream, out WebClient Client) { Client = new WebClient(); OutputStream = Client.OpenRead(FileName); } public static string GetFileContents(Uri FileName, string UserName, string Password) { using (WebClient Client = new WebClient()) { Client.Credentials = new NetworkCredential(UserName, Password); using (StreamReader Reader = new StreamReader(Client.OpenRead(FileName))) { string Contents = Reader.ReadToEnd(); Reader.Close(); return Contents; } } } public static void GetFileContents(Uri FileName, string UserName, string Password, out Stream OutputStream, out WebClient Client) { Client = new WebClient(); Client.Credentials = new NetworkCredential(UserName, Password); OutputStream = Client.OpenRead(FileName); } public static void GetFileContents(string FileName, out byte[] Output) { GetFileContents(FileName, out Output, 5000); } #endregion #region CopyDirectory public static void CopyDirectory(string Source, string Destination, bool Recursive, CopyOptions Options) { DirectoryInfo SourceInfo = new DirectoryInfo(Source); DirectoryInfo DestinationInfo = new DirectoryInfo(Destination); if (!DirectoryExists(Destination)) { CreateDirectory(Destination); } List<FileInfo> Files = FileList(Source); foreach (FileInfo File in Files) { if (Options == CopyOptions.CopyAlways) { File.CopyTo(Path.Combine(DestinationInfo.FullName, File.Name), true); } else if (Options == CopyOptions.CopyIfNewer) { if (FileExists(Path.Combine(DestinationInfo.FullName, File.Name))) { FileInfo FileInfo = new FileInfo(Path.Combine(DestinationInfo.FullName, File.Name)); if (FileInfo.LastWriteTime.CompareTo(File.LastWriteTime) < 0) { File.CopyTo(Path.Combine(DestinationInfo.FullName, File.Name), true); } } else { File.CopyTo(Path.Combine(DestinationInfo.FullName, File.Name), true); } } else if (Options == CopyOptions.DoNotOverwrite) { File.CopyTo(Path.Combine(DestinationInfo.FullName, File.Name), false); } } if (Recursive) { List<DirectoryInfo> Directories = DirectoryList(SourceInfo.FullName); foreach (DirectoryInfo Directory in Directories) { CopyDirectory(Directory.FullName, Path.Combine(DestinationInfo.FullName, Directory.Name), Recursive, Options); } } } #endregion #region GetDirectorySize public static long GetDirectorySize(string Directory, bool Recursive) { long Size = 0; List<FileInfo> Files = FileManager.FileList(Directory, Recursive); foreach (FileInfo File in Files) { Size += File.Length; } return Size; } #endregion #region DeleteFilesOlderThan public static void DeleteFilesOlderThan(string Directory, DateTime CompareDate, bool Recursive) { List<FileInfo> Files = FileManager.FileList(Directory, Recursive); foreach (FileInfo File in Files) { if (File.LastWriteTime < CompareDate) { FileManager.Delete(File.FullName); } } } #endregion #region DeleteFilesNewerThan public static void DeleteFilesNewerThan(string Directory, DateTime CompareDate, bool Recursive) { List<FileInfo> Files = FileManager.FileList(Directory, Recursive); foreach (FileInfo File in Files) { if (File.LastWriteTime > CompareDate) { FileManager.Delete(File.FullName); } } } #endregion #region CompareFiles public static bool CompareFiles(string FileName1, string FileName2) { FileInfo File1 = new FileInfo(FileName1); FileInfo File2 = new FileInfo(FileName2); if (File1.Length != File2.Length) { return false; } string File1Contents = FileManager.GetFileContents(FileName1); string File2Contents = FileManager.GetFileContents(FileName2); if (!File1Contents.Equals(File2Contents)) return false; return true; } #endregion #endregion } #region Enums public enum CopyOptions { CopyIfNewer, CopyAlways, DoNotOverwrite } #endregion }
下面是用Console Application来使用例子
using (Utilities.FileFormats.Zip.ZipFile File = new Utilities.FileFormats.Zip.ZipFile(@"E:\ZIPFILENAME.zip", true)) { File.AddFolder(@"E:\Emp"); File.AddFolder(@"E:\360Downloads\Silverlight"); } Console.WriteLine("Success"); Console.ReadKey();
这两个类,其实也是根据MIcrosoft中Packing类,就是第一种 方法,然后使其能对整个文件进行打包,但其AddFile方法不能成功!很可惜,不过这个应该不是大问题,估计花点时间还是会其调试好的。
这两个类打包后的文件其也有像第一种方法那样,有关联文件,而且没有去掉,估计其写这代码的人也暂时没有办法去掉,所以我也舍弃掉了!
主要参考了以下网址
Creating a Zip File in C#:http://www.gutgames.com/post/Creating-a-Zip-File-in-C.aspx
辅助类地址:http://www.quebeclogiciel.com/csUtil/Documentation/html/_file_manager_8cs_source.html
3. 用开源的SharpZipLib Library 来打包,这个可以打包,而且没有关联文件,根据这个类库,我改写和编写一个常用的类来打包及解压,下面是这个类的代码
Packing.cs
public class GPacking { private List<FileInfo> GetFileList(string sDirectoryPath, PackingScope scope) { List<FileInfo> filesInfo = new List<FileInfo>(); DirectoryInfo dir = new DirectoryInfo(sDirectoryPath); if (scope != PackingScope.Folder) { FileInfo[] files = dir.GetFiles(); foreach (FileInfo fTemp in files) { filesInfo.Add(fTemp); } } if (scope != PackingScope.File) { DirectoryInfo[] dirs = dir.GetDirectories(); foreach (DirectoryInfo dirTemp in dirs) { List<FileInfo> templist = GetFileList(dirTemp.FullName, PackingScope.All); foreach (FileInfo fileTemp in templist) { filesInfo.Add(fileTemp); } } } return filesInfo; } /// <summary> /// 把文件夹里面的文件为一个压缩包文件 /// </summary> /// <param name="sDirectoryPath">需要打包的目录</param> /// <param name="FileName">打包之后保存的文件名称,如D:\packing.zip</param> /// <param name="scope">打包的范围</param> /// <returns></returns> public bool ToFile(string sDirectoryPath, string FileName, PackingScope scope) { bool result = false; List<FileInfo> filesInfo = new List<FileInfo>(); Crc32 crc = new Crc32(); ZipOutputStream s = null; int i = 1; try { FileInfo filedd = new FileInfo(FileName); if (!Directory.Exists(filedd.Directory.FullName)) { Directory.CreateDirectory(filedd.Directory.FullName); } s = new ZipOutputStream(File.OpenWrite(FileName)); s.SetLevel(9); DirectoryInfo mainDir = new DirectoryInfo(sDirectoryPath); filesInfo = GetFileList(mainDir.FullName, scope); foreach (FileInfo file in filesInfo) { using (FileStream fs = File.OpenRead(file.FullName)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); ZipEntry entry = new ZipEntry(ZipEntry.CleanName(file.FullName.Replace(mainDir.FullName + "\\", ""))); entry.DateTime = DateTime.Now; entry.Comment = i.ToString(); entry.ZipFileIndex = i++; entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } s.Finish(); s.Close(); } catch (Exception ex) { throw new Exception(ex.Message); } finally { s.Close(); } return result; } /// <summary> /// 把一个文件打包 /// </summary> /// <param name="sFileFullPath">文件的全路径</param> /// <param name="FileName">打包之后保存的文件名称</param> /// <returns></returns> public bool ToFile(string sFileFullPath, string FileName) { bool result = false; Crc32 crc = new Crc32(); ZipOutputStream s = null; int i = 1; try { FileInfo filedd = new FileInfo(FileName); //DirectoryInfo mainDir = new DirectoryInfo(sDirectoryPath); if (!Directory.Exists(filedd.Directory.FullName)) { Directory.CreateDirectory(filedd.Directory.FullName); } s = new ZipOutputStream(File.OpenWrite(FileName)); s.SetLevel(9); FileInfo file = new FileInfo(sFileFullPath); using (FileStream fs = File.OpenRead(file.FullName)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); ZipEntry entry = new ZipEntry(ZipEntry.CleanName(file.Name)); entry.DateTime = DateTime.Now; entry.Comment = i.ToString(); entry.ZipFileIndex = i++; entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } s.Finish(); s.Close(); } catch (Exception ex) { throw new Exception(ex.Message); } finally { s.Close(); } return result; } /// <summary> /// 解压文件 /// </summary> /// <param name="zipPathAndFile">需要解压文件的路径</param> /// <param name="outputFolder">解压到哪里</param> /// <param name="deleteZipFile">是否删除</param> public void UnZipFiles(string zipPathAndFile, string outputFolder, bool deleteZipFile) { ZipInputStream s = new ZipInputStream(File.OpenRead(zipPathAndFile)); ZipEntry theEntry; string tmpEntry = String.Empty; while ((theEntry = s.GetNextEntry()) != null) { string directoryName = outputFolder; string fileName = Path.GetFileName(theEntry.Name); // create directory if (directoryName != "") { Directory.CreateDirectory(directoryName); } if (fileName != String.Empty) { if (theEntry.Name.IndexOf(".ini") < 0) { string fullPath = directoryName + "\\" + theEntry.Name; fullPath = fullPath.Replace("\\ ", "\\"); string fullDirPath = Path.GetDirectoryName(fullPath); if (!Directory.Exists(fullDirPath)) Directory.CreateDirectory(fullDirPath); Console.WriteLine(System.Web.HttpUtility.UrlDecode(fullPath)); FileStream streamWriter = File.Create(System.Web.HttpUtility.UrlDecode(fullPath)); int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); } } } s.Close(); if (deleteZipFile) File.Delete(zipPathAndFile); } } public enum PackingScope { Folder, File, All }
在Packing里需 引用以下命名空间:
using System.Text; using System.IO; using ICSharpCode.SharpZipLib.Zip; using ICSharpCode.SharpZipLib.Checksums;
其中ICShareCode开头的命令空间,你可以通过以下参考地址来查看其源代码,或者你可以通过以下链接来下载,我已经编译好的DLL文件
ICSharpCode.SharpZipLib.zip
引用DLL后你可以通以下代码来实现解压与打包
GPacking gpk = new GPacking(); gpk.ToFile(@"E:\WebApplication1\bin\Emp", @"e:\abc\mypp.rar", PackingScope.File); Console.WriteLine("Success"); //gpk.UnZipFiles(@"E:\abc\asfsa\ZIPFILENAME.zip",@"E:\dd",true); //Console.WriteLine("Success"); Console.ReadKey();
下面详细地讲解阐述一下我现在用的这个类的一些参数及方法
PackingScope: 这个是打包的范围,有三种可能File,Folder,All (这是我自己定义的枚举例子),File表示只打包这个要打包文件夹的根目录的文件(不包含文件夹,及文件夹的子文件), Folder表示只打包要打包文件夹的子文件夹及子文件夹的文件,文件夹即除了File打包的的所有文件), ALL表示其所有的都打包。
另一重载方法中ToFile(只打包单一的文件)
下面是库源文件的地址和在开发过程中参考的地址:
源文件下载地址及帮助文档地址:http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx
这个库的参考打包代码地址:http://geekswithblogs.net/twickers/archive/2005/11/08/59420.aspx