日期:2014-05-18  浏览次数:20813 次

C# 压缩 打包程序
给一个文件夹,文件夹包含子文件夹及子文件,如何用C#写一个打包程序,把所有的文件及路径打包变为一个文件?
最好不要调用WinRAR.exe等现成软件,因为我还需要在单片机及ARM中把它解压出来!
多多提提方案!
谢谢各位大虾!

------解决方案--------------------
自己定义一个文件结构。然后把所有的文件读进来,再根据这个结构写到一个文件中去。
C# code

    class CZipFileHeader
    {
        private const int MAX_PATH = 255;

        public char[]  m_cName; //File name. length:255
        public long  m_lStartPos; //Start position
        public long  m_lSize; //File size

        public CZipFileHeader()
        {
            m_cName = new char[MAX_PATH];
        }
    }

------解决方案--------------------
ICSharpCode.SharpZipLib.dll
------解决方案--------------------
C# code
///  <summary> 
/// 压缩和解压文件
/// </summary>
public class ZipClass
{
  /// <summary>
  /// 所有文件缓存
  /// </summary>
  List <string> files = new List <string>();

  /// <summary>
  /// 所有空目录缓存
  /// </summary>
  List <string> paths = new List <string>();

  /// <summary>
  /// 压缩单个文件
  /// </summary>
  /// <param name="fileToZip">要压缩的文件 </param>
  /// <param name="zipedFile">压缩后的文件全名 </param>
  /// <param name="compressionLevel">压缩程度,范围0-9,数值越大,压缩程序越高 </param>
  /// <param name="blockSize">分块大小 </param>
  public void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)
  {
    if (!System.IO.File.Exists(fileToZip))//如果文件没有找到,则报错
    {
      throw new FileNotFoundException("The specified file " + fileToZip + " could not be found. Zipping aborderd");
    }

    FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read);
    FileStream zipFile = File.Create(zipedFile);
    ZipOutputStream zipStream = new ZipOutputStream(zipFile);
    ZipEntry zipEntry = new ZipEntry(fileToZip);
    zipStream.PutNextEntry(zipEntry);
    zipStream.SetLevel(compressionLevel);
    byte[] buffer = new byte[blockSize];
    int size = streamToZip.Read(buffer, 0, buffer.Length);
    zipStream.Write(buffer, 0, size);

    try
    {
      while (size < streamToZip.Length)
      {
        int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
        zipStream.Write(buffer, 0, sizeRead);
        size += sizeRead;
      }
    }
    catch (Exception ex)
    {
      GC.Collect();
      throw ex;
    }

    zipStream.Finish();
    zipStream.Close();
    streamToZip.Close();
    GC.Collect();
  }

  /// <summary>
  /// 压缩目录(包括子目录及所有文件)
  /// </summary>
  /// <param name="rootPath">要压缩的根目录 </param>
  /// <param name="destinationPath">保存路径 </param>
  /// <param name="compressLevel">压缩程度,范围0-9,数值越大,压缩程序越高 </param>
  public void ZipFileFromDirectory(string rootPath, string destinationPath, int compressLevel)