递归实现压缩文件夹和子文件夹。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;
using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary; namespace CommonBaseInfo
{
public class Zip
{ #region 压缩解压单一文件
/// <summary>
/// 压缩单一文件
/// </summary>
/// <param name="sourceFile">源文件路径</param>
/// <param name="destinationFile">目标文件路径</param>
public static void CompressFile(string sourceFile, string destinationFile)
{
if (!File.Exists(sourceFile)) throw new FileNotFoundException();
using (FileStream sourceStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read))
{
byte[] buffer = new byte[sourceStream.Length];
int checkCounter = sourceStream.Read(buffer, , buffer.Length);
if (checkCounter != buffer.Length) throw new ApplicationException();
using (FileStream destinationStream = new FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.Write))
{
using (GZipStream compressedStream = new GZipStream(destinationStream, CompressionMode.Compress, true))
{
compressedStream.Write(buffer, , buffer.Length);
}
}
}
}
public static void CompressFile(byte[] source, string destinationFile)
{
using (FileStream destinationStream = new FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.Write))
{
using (GZipStream compressedStream = new GZipStream(destinationStream, CompressionMode.Compress, true))
{
compressedStream.Write(source, , source.Length);
}
}
} /// <summary>
/// 解压缩文件
/// </summary>
/// <param name="sourceFile">源文件路径</param>
/// <param name="destinationFile">目标文件路径</param>
public static void DecompressFile(string sourceFile, string destinationFile)
{
if (!File.Exists(sourceFile)) throw new FileNotFoundException();
using (FileStream sourceStream = new FileStream(sourceFile, FileMode.Open))
{
byte[] quartetBuffer = new byte[];
int position = (int)sourceStream.Length - ;
sourceStream.Position = position;
sourceStream.Read(quartetBuffer, , );
sourceStream.Position = ;
int checkLength = BitConverter.ToInt32(quartetBuffer, );
byte[] buffer = new byte[checkLength + ];
using (GZipStream decompressedStream = new GZipStream(sourceStream, CompressionMode.Decompress, true))
{
int total = ;
for (int offset = ; ; )
{
int bytesRead = decompressedStream.Read(buffer, offset, );
if (bytesRead == ) break;
offset += bytesRead;
total += bytesRead;
}
using (FileStream destinationStream = new FileStream(destinationFile, FileMode.Create))
{
destinationStream.Write(buffer, , total);
destinationStream.Flush();
}
}
}
} #endregion #region 压缩解压文件夹
/**/
/// <summary>
/// 对目标文件夹进行压缩,将压缩结果保存为指定文件
/// </summary>
/// <param name="dirPath">目标文件夹</param>
/// <param name="fileName">压缩文件</param>
/// public static void CompressFolderP(string dirPath, string fileName)
{
ArrayList list = new ArrayList();
CompressFolder(dirPath, fileName, dirPath,list); }
public static void CompressFolder(string dirPath, string fileName, string rootdir, ArrayList list)
{ foreach (string d in Directory.GetDirectories(dirPath))
{
byte[] destBuffer = null;
string path = d.Replace(rootdir, "");
SerializeFileInfo sfi = new SerializeFileInfo(d, destBuffer, "",path);
list.Add(sfi);
CompressFolder(d, fileName,rootdir,list); } foreach (string f in Directory.GetFiles(dirPath))
{ if ( (File.GetAttributes(f) & FileAttributes.Hidden) != FileAttributes.Hidden)
{
byte[] destBuffer = File.ReadAllBytes(f);
string path = f.Replace(rootdir, "");
SerializeFileInfo sfi = new SerializeFileInfo(f, destBuffer, "", path);
list.Add(sfi);
} } IFormatter formatter = new BinaryFormatter();
using (Stream s = new MemoryStream())
{
formatter.Serialize(s, list);
s.Position = ;
CreateCompressFile(s, fileName);
}
}
/**/
/// <summary>
/// 对目标压缩文件解压缩,将内容解压缩到指定文件夹
/// </summary>
/// <param name="fileName">压缩文件</param>
/// <param name="dirPath">解压缩目录</param>
/// public static void DeCompressFolder(string fileName, string dirPath)
{ if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
} using (Stream source = File.OpenRead(fileName))
{
using (Stream destination = new MemoryStream())
{
using (GZipStream input = new GZipStream(source, CompressionMode.Decompress, true))
{
byte[] bytes = new byte[];
int n;
while ((n = input.Read(bytes, , bytes.Length)) != )
{
destination.Write(bytes, , n);
}
}
destination.Flush();
destination.Position = ;
DeSerializeFiles(destination, dirPath);
}
}
}
private static void DeSerializeFiles(Stream s, string dirPath)
{
BinaryFormatter b = new BinaryFormatter();
ArrayList list = (ArrayList)b.Deserialize(s);
foreach (SerializeFileInfo f in list)
{
if (f.Fileflag == "")
{
string newName = dirPath + f.Filedirnane;
using (FileStream fs = new FileStream(newName, FileMode.Create, FileAccess.Write))
{
fs.Write(f.FileBuffer, , f.FileBuffer.Length);
fs.Close();
}
}
else
{
if (!Directory.Exists(dirPath+f.Filedirnane))
{
Directory.CreateDirectory(dirPath + f.Filedirnane);
} }
}
}
private static void CreateCompressFile(Stream source, string destinationName)
{
using (Stream destination = new FileStream(destinationName, FileMode.Create, FileAccess.Write))
{
using (GZipStream output = new GZipStream(destination, CompressionMode.Compress))
{
byte[] bytes = new byte[];
int n;
while ((n = source.Read(bytes, , bytes.Length)) != )
{
output.Write(bytes, , n);
}
}
}
} #endregion [Serializable]
class SerializeFileInfo
{
public SerializeFileInfo(string name, byte[] buffer,string flag,string dirname)
{
fileName = name;
fileBuffer = buffer;
fileflag = flag;
filedirnane = dirname;
}
string fileflag;
string filedirnane;
string fileName; public string Filedirnane
{
get
{
return filedirnane;
}
}
public string Fileflag
{
get
{
return fileflag;
}
} public string FileName
{
get
{
return fileName;
}
}
byte[] fileBuffer;
public byte[] FileBuffer
{
get
{
return fileBuffer;
}
}
}
}
}
 CommonBaseInfo.Zip.CompressFolderP(@"c:\debug", @"c:\debug.zip");
CommonBaseInfo.Zip.DeCompressFolder(@"c:\debug.zip", @"c:\debug\");

c# 压缩文件的更多相关文章

  1. 【VC++技术杂谈008】使用zlib解压zip压缩文件

    最近因为项目的需要,要对zip压缩文件进行批量解压.在网上查阅了相关的资料后,最终使用zlib开源库实现了该功能.本文将对zlib开源库进行简单介绍,并给出一个使用zlib开源库对zip压缩文件进行解 ...

  2. C#基础-压缩文件及故障排除

    C#压缩文件可以使用第三方dll库:ICSharpCode.SharpZipLib.dll: 以下代码能实现文件夹与多个文件的同时压缩.(例:把三个文件夹和五个文件一起压缩成一个zip) 直接上代码, ...

  3. 破解压缩文件密码rarcrack

    破解压缩文件密码rarcrack   常见的压缩文件格式有ZIP.RAR和7z.这三种格式都支持使用密码进行加密压缩.前面讲过破解ZIP压缩文件,可以使用fcrackzip.对于RAR和7z格式,可以 ...

  4. 文件打包,下载之使用PHP自带的ZipArchive压缩文件并下载打包好的文件

    总结:                                                          使用PHP下载文件的操作需要给出四个header(),可以参考我的另一篇博文: ...

  5. java ZipOutputStream压缩文件,ZipInputStream解压缩

    java中实现zip的压缩与解压缩.java自带的 能实现的功能比较有限. 本程序功能:实现简单的压缩和解压缩,压缩文件夹下的所有文件(文件过滤的话需要对File进一步细节处理). 对中文的支持需要使 ...

  6. C# 压缩文件与字节互转

    public class ZipBin { public byte[] bytes; //C#读取压缩文件(将压缩文件转换为二进制 public void GetZipToByte(string in ...

  7. Linux如何复制,打包,压缩文件

    (1)复制文件 cp -r  要copy的文件/("/"指的是包括里面的内容)   newfile_name(要命名的文件名) eg:cp -r webapps_zero/   f ...

  8. java生成压缩文件

    在工作过程中,需要将一个文件夹生成压缩文件,然后提供给用户下载.所以自己写了一个压缩文件的工具类.该工具类支持单个文件和文件夹压缩.放代码: import java.io.BufferedOutput ...

  9. 7z压缩文件时排除指定的文件

    分享一个7z压缩文件时排除指定文件类型的命令行,感觉很有用: 7z a -t7z d:\updateCRM.7z d:\updateCRM\*.* -r -x!*.log -x!*bak a:创建压缩 ...

  10. [Java 基础] 使用java.util.zip包压缩和解压缩文件

    reference :  http://www.open-open.com/lib/view/open1381641653833.html Java API中的import java.util.zip ...

随机推荐

  1. poj3050

    #include <stdio.h> #include <set> #include <string> using namespace std; int a[6]; ...

  2. [转载~笔记]CentOS单独编译安装PHP gd库扩展

    http://www.nowamagic.net/librarys/veda/detail/2610 安装gd前置库: freetype, jpegsrc, libpng 1. freetypewge ...

  3. 初学layer-------web框架

    第一步,文件的下载   http://layer.layui.com/ 第二步,文件的部署即将包放到web端的相关目录下. 第三步,引用layer.js(此框架是基于jquery的)所以要先引用jqu ...

  4. 利用ManualResetEvent来来控制异步调用的打印的线程的暂停和恢复(转)

    利用ManualResetEvent来来控制异步调用的打印的线程的暂停和恢复 打印过程可能很长,这时候有可能需要暂停下来做一些事情,然后回来继续接着打印 打印过程中有2个线程:一个是程序运行的主线程, ...

  5. Linux下的网络远程安装

    Linux下的网络远程安装 1.用RHEL6.5光盘安装第一台服务器 2.在第一台服务器上配置YUM服务器 先创建一个挂载 #mount #umount /dev/cdrom #mkdir /mnt/ ...

  6. String reorder

    本问题出自:微软2014实习生及秋令营技术类职位在线测试 (Microsoft Online Test for Core Technical Positions) Description For th ...

  7. 写在Ruby之前。

    jeiao: 入行程序员也有一年的时间,入门的时候学的Java,在公司写了大半年的Java,也主要是Web方向,使用过struts2 做过项目,后来又用SSH实现了一遍,感觉就那么点意思,因为公司规模 ...

  8. vijos1144(小胖守皇宫)

    也是ural1039 描述 huyichen世子事件后,xuzhenyi成了皇上特聘的御前一品侍卫. 皇宫以午门为起点,直到后宫嫔妃们的寝宫,呈一棵树的形状:某些宫殿间可以互相望见.大内保卫森严,三步 ...

  9. [Leetcode][JAVA] Pascal's Triangle I, II

    Pascal's Triangle: Given numRows, generate the first numRows of Pascal's triangle. For example, give ...

  10. 人脸识别经典算法二:LBP方法

    与第一篇博文特征脸方法不同,LBP(Local Binary Patterns,局部二值模式)是提取局部特征作为判别依据的.LBP方法显著的优点是对光照不敏感,但是依然没有解决姿态和表情的问题.不过相 ...