using System;
using System.IO;
using System.IO.Packaging; namespace Utility
{
public class ZipHelper
{
///<summary>
/// Add a folder along with its subfolders to a Package
/// </summary>
/// <param name="folderName">The folder to add</param>
/// <param name="compressedFileName">The package to create</param>
/// <param name="overrideExisting">Override exsisitng files</param>
/// <returns></returns>
public static bool PackageFolder(string folderName, string compressedFileName, bool overrideExisting)
{
if (folderName.EndsWith(@"\"))
folderName = folderName.Remove(folderName.Length - );
bool result = false;
if (!Directory.Exists(folderName))
{
return result;
} if (!overrideExisting && File.Exists(compressedFileName))
{
return result;
}
try
{
using (Package package = Package.Open(compressedFileName, FileMode.Create))
{
var fileList = Directory.EnumerateFiles(folderName, "*", SearchOption.AllDirectories);
foreach (string fileName in fileList)
{ //The path in the package is all of the subfolders after folderName
string pathInPackage;
pathInPackage = Path.GetDirectoryName(fileName).Replace(folderName, string.Empty) + "/" + Path.GetFileName(fileName); Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(pathInPackage, UriKind.Relative));
PackagePart packagePartDocument = package.CreatePart(partUriDocument, "", CompressionOption.Maximum);
using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
fileStream.CopyTo(packagePartDocument.GetStream());
}
}
}
result = true;
}
catch (Exception e)
{
throw new Exception("Error zipping folder " + folderName, e);
} return result;
}
}
}
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.IO; namespace Utility
{
/// <summary>
/// 需要引用NuGet包:ICSharpCode.SharpZipLib
/// </summary>
public class ZipNewHelper
{
public void ZipFile(string strFile, string strZip)
{
if (strFile[strFile.Length - ] != Path.DirectorySeparatorChar)
strFile += Path.DirectorySeparatorChar;
ZipOutputStream s = new ZipOutputStream(File.Create(strZip));
s.SetLevel(); // 0 - store only to 9 - means best compression
zip(strFile, s, strFile);
s.Finish();
s.Close();
} private void zip(string strFile, ZipOutputStream s, string staticFile)
{
if (strFile[strFile.Length - ] != Path.DirectorySeparatorChar) strFile += Path.DirectorySeparatorChar;
Crc32 crc = new Crc32();
string[] filenames = Directory.GetFileSystemEntries(strFile);
foreach (string file in filenames)
{ if (Directory.Exists(file))
{
zip(file, s, staticFile);
} else // 否则直接压缩文件
{
//打开压缩文件
FileStream fs = File.OpenRead(file); byte[] buffer = new byte[fs.Length];
fs.Read(buffer, , buffer.Length);
string tempfile = file.Substring(staticFile.LastIndexOf("\\") + );
ZipEntry entry = new ZipEntry(tempfile); entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
s.PutNextEntry(entry); s.Write(buffer, , buffer.Length);
}
}
}
}
}
using System;
using System.IO; namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string parentDir = @"E:\92-收藏文档\C#";
DeleteFiles(parentDir);
} public static void DeleteFiles(string str)
{
DirectoryInfo fatherFolder = new DirectoryInfo(str);
//删除子文件夹
//DirectoryInfo[] childFolders = fatherFolder.GetDirectories();
//foreach (DirectoryInfo dir in childFolders)
//{
// try
// {
// string dirName = dir.Name;
// if (dirName.Contains("obj"))
// {
// Directory.Delete(dir.FullName, true);
// }
// }
// catch (Exception ex)
// { }
//} //删除当前文件夹内文件
FileInfo[] files = fatherFolder.GetFiles();
foreach (FileInfo file in files)
{
//string fileName = file.FullName.Substring((file.FullName.LastIndexOf("\\") + 1), file.FullName.Length - file.FullName.LastIndexOf("\\") - 1);
string fileName = file.Name;
try
{
if (fileName.Contains("cs"))
{
//File.Delete(file.FullName);
string path = file.FullName;
//Path.ChangeExtension(path, "txt");
File.Move(path, Path.ChangeExtension(path, "txt"));
}
}
catch (Exception ex)
{
}
} //递归删除子文件夹内文件
foreach (DirectoryInfo childFolder in fatherFolder.GetDirectories())
{
DeleteFiles(childFolder.FullName);
}
}
}
}

C# 文件压缩方法的更多相关文章

  1. linux服务器的Gzip文件压缩方法[转]

    一.gzip介绍 gzip是GNU zip的缩写,它是一个GNU自由软件的文件压缩程序,也经常用来表示gzip这种文件格式.软件的作者是Jean-loup Gailly和Mark Adler.1992 ...

  2. 虚拟磁盘VHD文件压缩方法

    问题描述 因工作需要在Mac上跑了一个VirtualBox虚拟win7,使用对win系统友好的vhd格式作为虚拟硬盘.经过一段时间使用发现vhd占用空间远大于虚拟磁盘使用量,想办法减减肥才行. 步骤整 ...

  3. c#自带压缩类实现数据库表导出到CSV压缩文件的方法

    在导出大量CSV数据的时候,常常体积较大,采用C#自带的压缩类,可以方便的实现该功能,并且压缩比例很高,该方法在我的开源工具DataPie中已经经过实践检验.我的上一篇博客<功能齐全.效率一流的 ...

  4. ASP.Net MVC_DotNetZip简单使用方法,解决文件压缩的问题[转]

    准备工作: 在vs工具栏中找到NuGet   下载DotNetZip   现在就可以使用DotNetZip强大的类库了,在这里我给出一些简单的使用. ? 1 2 3 4 5 6 7 8 9 10 11 ...

  5. 使用zip压缩文件夹方法

    最近使用MapGis对.MPJ工程文件文件裁剪后,要对裁剪后的图形文件.ML,.MT,.MP,.MPJ文件打包,在网上找到7zip,Zlib的库,虽然都有源码,但是Zlib库中的使用没找到文件压缩的函 ...

  6. python用模块zlib压缩与解压字符串和文件的方法

    摘自:http://www.jb51.net/article/100218.htm Python标准模块中,有多个模块用于数据的压缩与解压缩,如zipfile,gzip, bz2等等. python中 ...

  7. php多文件压缩下载

    /*php多文件压缩并且下载*/ function addFileToZip($path,$zip){ $handler=opendir($path); //打开当前文件夹由$path指定. whil ...

  8. Zip文件压缩(加密||非加密||压缩指定目录||压缩目录下的单个文件||根据路径压缩||根据流压缩)

    1.写入Excel,并加密压缩.不保存文件 String dcxh = String.format("%03d", keyValue); String folderFileName ...

  9. Java实现文件压缩与解压

    Java实现ZIP的解压与压缩功能基本都是使用了Java的多肽和递归技术,可以对单个文件和任意级联文件夹进行压缩和解压,对于一些初学者来说是个很不错的实例.(转载自http://www.puiedu. ...

随机推荐

  1. 洛谷——P1007 独木桥

    P1007 独木桥 题目背景 战争已经进入到紧要时间.你是运输小队长,正在率领运输部队向前线运送物资.运输任务像做题一样的无聊.你希望找些刺激,于是命令你的士兵们到前方的一座独木桥上欣赏风景,而你留在 ...

  2. Cisco网络设备命名规则

      1. CISCO 开头的产品都是路由器:2. RSP 开头的都是CISCO7500 系列产品的引擎:3. VIP 开头的产品都是CISCO 7500系列产品的多功能接口处理器模块:4. PA 开头 ...

  3. flask应用的分页

    Flask-SQLAlchemy支持分页 https://www.jianshu.com/p/5e03cd202728

  4. C++之类的比較运算符的重载

    比較运算符的重载通常有两种方式: 第一:作为成员函数重载 曾经几章的Student类为例: <span style="font-family:Microsoft YaHei;font- ...

  5. [React] Prevent Unnecessary Rerenders of Compound Components using React Context

    Due to the way that React Context Providers work, our current implementation re-renders all our comp ...

  6. 1062. Talent and Virtue (25)【排序】——PAT (Advanced Level) Practise

    题目信息 1062. Talent and Virtue (25) 时间限制200 ms 内存限制65536 kB 代码长度限制16000 B About 900 years ago, a Chine ...

  7. java struts jxl 导入导出Excel(无模板)

    jar包: import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.io.Fil ...

  8. JavaScript基础 -- js常用内置方法和对象

    JS中常用的内置函数如下: 1.eval(str):计算表达式的结果. 2.parseInt(str,n):将符串转换成整数数字形式(可指定几进制). 3.parseFloat(str):将字符串转换 ...

  9. iOS开发——高级篇——iOS 强制退出程序APP代码

    1.先po代码 UIAlertView* alert = [[UIAlertView alloc] initWithTitle:self.exitapplication message:@" ...

  10. HDU 5475An easy problem 离线set/线段树

    An easy problem Time Limit: 8000/5000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others) ...