C#文件压缩:ICSharpCode.SharpZipLib生成zip、tar、tar.gz
原文地址:https://blog.csdn.net/nihao198503/article/details/9204115
将代码原封不动的copy过来,只是因为有关tar的文章太少,大多都是zip的文章
/// <summary>
/// 生成 ***.tar.gz 文件
/// </summary>
/// <param name="strBasePath">文件基目录(源文件、生成文件所在目录)</param>
/// <param name="strSourceFolderName">待压缩的源文件夹名</param>
public bool CreatTarGzArchive(string strBasePath, string strSourceFolderName)
{
if (string.IsNullOrEmpty(strBasePath)
|| string.IsNullOrEmpty(strSourceFolderName)
|| !System.IO.Directory.Exists(strBasePath)
|| !System.IO.Directory.Exists(Path.Combine(strBasePath, strSourceFolderName)))
{
return false;
} Environment.CurrentDirectory = strBasePath;
string strSourceFolderAllPath = Path.Combine(strBasePath, strSourceFolderName);
string strOupFileAllPath = Path.Combine(strBasePath, strSourceFolderName + ".tar.gz"); Stream outTmpStream = new FileStream(strOupFileAllPath, FileMode.OpenOrCreate); //注意此处源文件大小大于4096KB
Stream outStream = new GZipOutputStream(outTmpStream);
TarArchive archive = TarArchive.CreateOutputTarArchive(outStream, TarBuffer.DefaultBlockFactor);
TarEntry entry = TarEntry.CreateEntryFromFile(strSourceFolderAllPath);
archive.WriteEntry(entry, true); if (archive != null)
{
archive.Close();
} outTmpStream.Close();
outStream.Close(); return true;
}
生成 ***.tar.gz 文件
/// <summary>
/// 文件解压
/// </summary>
/// <param name="zipPath">压缩文件路径</param>
/// <param name="goalFolder">解压到的目录</param>
/// <returns></returns>
public static bool UnzipTgz(string zipPath, string goalFolder)
{
Stream inStream = null;
Stream gzipStream = null;
TarArchive tarArchive = null;
try
{
using (inStream = File.OpenRead(zipPath))
{
using (gzipStream = new GZipInputStream(inStream))
{
tarArchive = TarArchive.CreateInputTarArchive(gzipStream);
tarArchive.ExtractContents(goalFolder);
tarArchive.Close();
}
}
return true;
}
catch (Exception ex)
{
Console.WriteLine("压缩出错!");
return false;
}
finally
{
if (null != tarArchive) tarArchive.Close();
if (null != gzipStream) gzipStream.Close();
if (null != inStream) inStream.Close();
}
}
tar.gz解压
/// <summary>
/// 生成 ***.tar 文件
/// </summary>
/// <param name="strBasePath">文件基目录(源文件、生成文件所在目录)</param>
/// <param name="strSourceFolderName">待压缩的源文件夹名</param>
public bool CreatTarArchive(string strBasePath, string strSourceFolderName)
{
if (string.IsNullOrEmpty(strBasePath)
|| string.IsNullOrEmpty(strSourceFolderName)
|| !System.IO.Directory.Exists(strBasePath)
|| !System.IO.Directory.Exists(Path.Combine(strBasePath, strSourceFolderName)))
{
return false;
} Environment.CurrentDirectory = strBasePath;
string strSourceFolderAllPath = Path.Combine(strBasePath, strSourceFolderName);
string strOupFileAllPath = Path.Combine(strBasePath, strSourceFolderName + ".tar"); Stream outStream = new FileStream(strOupFileAllPath, FileMode.OpenOrCreate); TarArchive archive = TarArchive.CreateOutputTarArchive(outStream, TarBuffer.DefaultBlockFactor);
TarEntry entry = TarEntry.CreateEntryFromFile(strSourceFolderAllPath);
archive.WriteEntry(entry, true); if (archive != null)
{
archive.Close();
} outStream.Close(); return true;
}
生成 ***.tar文件(针对文件夹)
/// <summary>
/// 生成tar文件
/// </summary>
/// <param name="strBasePath">文件夹路径——将被压缩的文件所在的地方</param>
/// <param name="listFilesPath">文件的路径:H:\Demo\xxx.txt</param>
/// <param name="tarFileName">压缩后tar文件名称</param>
/// <returns></returns>
public static bool CreatTarArchive(string strBasePath, List<string> listFilesPath, string tarFileName)//"20180524" + ".tar"
{
if (string.IsNullOrEmpty(strBasePath) || string.IsNullOrEmpty(tarFileName) || !System.IO.Directory.Exists(strBasePath))
return false; Environment.CurrentDirectory = strBasePath;
string strOupFileAllPath = strBasePath + tarFileName;//一个完整的文件路径 .tar
Stream outStream = new FileStream(strOupFileAllPath, FileMode.OpenOrCreate);//打开.tar文件
TarArchive archive = TarArchive.CreateOutputTarArchive(outStream, TarBuffer.DefaultBlockFactor); for (int i = ; i < listFilesPath.Count; i++)
{
string fileName = listFilesPath[i];
TarEntry entry = TarEntry.CreateEntryFromFile(fileName);//将文件写到.tar文件中去
archive.WriteEntry(entry, true);
} if (archive != null)
{
archive.Close();
} outStream.Close(); return true;
}
生成tar文件(针对于多个文件)
/// <summary>
/// tar包解压
/// </summary>
/// <param name="strFilePath">tar包路径</param>
/// <param name="strUnpackDir">解压到的目录</param>
/// <returns></returns>
public static bool UnpackTarFiles(string strFilePath, string strUnpackDir)
{
try
{
if (!File.Exists(strFilePath))
{
return false;
} strUnpackDir = strUnpackDir.Replace("/", "\\");
if (!strUnpackDir.EndsWith("\\"))
{
strUnpackDir += "\\";
} if (!Directory.Exists(strUnpackDir))
{
Directory.CreateDirectory(strUnpackDir);
} FileStream fr = new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
DhcEc.SharpZipLib.Tar.TarInputStream s = new DhcEc.SharpZipLib.Tar.TarInputStream(fr);
DhcEc.SharpZipLib.Tar.TarEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name); if (directoryName != String.Empty)
Directory.CreateDirectory(strUnpackDir + directoryName); if (fileName != String.Empty)
{
FileStream streamWriter = File.Create(strUnpackDir + theEntry.Name); int size = ;
byte[] data = new byte[];
while (true)
{
size = s.Read(data, , data.Length);
if (size > )
{
streamWriter.Write(data, , size);
}
else
{
break;
}
} streamWriter.Close();
}
}
s.Close();
fr.Close(); return true;
}
catch (Exception)
{
return false;
}
}
tar包解压
/// <summary>
/// zip压缩文件
/// </summary>
/// <param name="filename">filename生成的文件的名称,如:C\123\123.zip</param>
/// <param name="directory">directory要压缩的文件夹路径</param>
/// <returns></returns>
public static bool PackFiles(string filename, string directory)
{
try
{
directory = directory.Replace("/", "\\"); if (!directory.EndsWith("\\"))
directory += "\\";
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
if (File.Exists(filename))
{
File.Delete(filename);
} FastZip fz = new FastZip();
fz.CreateEmptyDirectories = true;
fz.CreateZip(filename, directory, true, ""); return true;
}
catch (Exception)
{
return false;
}
}
zip压缩文件
/// <summary>
/// zip解压文件
/// </summary>
/// <param name="file">压缩文件的名称,如:C:\123\123.zip</param>
/// <param name="dir">dir要解压的文件夹路径</param>
/// <returns></returns>
public static bool UnpackFiles(string file, string dir)
{
try
{
if (!File.Exists(file))
return false; dir = dir.Replace("/", "\\");
if (!dir.EndsWith("\\"))
dir += "\\"; if (!Directory.Exists(dir))
Directory.CreateDirectory(dir); FileStream fr = new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
DhcEc.SharpZipLib.Zip.ZipInputStream s = new DhcEc.SharpZipLib.Zip.ZipInputStream(fr);
DhcEc.SharpZipLib.Zip.ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name); if (directoryName != String.Empty)
Directory.CreateDirectory(dir + directoryName); if (fileName != String.Empty)
{
FileStream streamWriter = File.Create(dir + theEntry.Name); int size = ;
byte[] data = new byte[];
while (true)
{
size = s.Read(data, , data.Length);
if (size > )
{
streamWriter.Write(data, , size);
}
else
{
break;
}
} streamWriter.Close();
}
}
s.Close();
fr.Close(); return true;
}
catch (Exception)
{
return false;
}
}
zip解压文件
/// <summary>
/// 压缩文件夹
/// </summary>
/// <param name="DirectoryToZip">需要压缩的文件夹(绝对路径)</param>
/// <param name="ZipedPath">压缩后的文件路径(绝对路径)</param>
/// <param name="ZipedFileName">>压缩后的文件名称(文件名,默认 同源文件夹同名)</param>
public static void ZipDirectory(string DirectoryToZip, string ZipedPath, string ZipedFileName = "")
{
//如果目录不存在,则报错
if (!System.IO.Directory.Exists(DirectoryToZip))
{
throw new System.IO.FileNotFoundException("指定的目录: " + DirectoryToZip + " 不存在!");
}
//文件名称(默认同源文件名称相同)
string ZipFileName = string.IsNullOrEmpty(ZipedFileName) ? ZipedPath + "\\" + new DirectoryInfo(DirectoryToZip).Name + ".zip" : ZipedPath + "\\" + ZipedFileName + ".zip";
using (System.IO.FileStream ZipFile = System.IO.File.Create(ZipFileName))
{
using (ZipOutputStream s = new ZipOutputStream(ZipFile))
{
ZipSetp(DirectoryToZip, s, "");
}
}
} /// <summary>
/// 递归遍历目录
/// </summary>
private static void ZipSetp(string strDirectory, ZipOutputStream s, string parentPath)
{
if (strDirectory[strDirectory.Length - ] != Path.DirectorySeparatorChar)
{
strDirectory += Path.DirectorySeparatorChar;
}
Crc32 crc = new Crc32();
string[] filenames = Directory.GetFileSystemEntries(strDirectory);
foreach (string file in filenames)// 遍历所有的文件和目录
{
if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
{
string pPath = parentPath;
pPath += file.Substring(file.LastIndexOf("\\") + );
pPath += "\\";
ZipSetp(file, s, pPath);
}
else // 否则直接压缩文件
{
//打开压缩文件
using (FileStream fs = File.OpenRead(file))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, , buffer.Length);
string fileName = parentPath + file.Substring(file.LastIndexOf("\\") + );
ZipEntry entry = new ZipEntry(fileName);
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);
}
}
}
}
将文件夹压缩成zip
使用C#自带类库对单个文件进行解压缩(rar)
public void YaSuo()
{
using (FileStream fsRead = File.OpenRead(@"F:\MVC5_Demo\Project4YaSuo\Project4YaSuo\Files\笔记.txt"))
{
//创建写入文件的流
using (FileStream fsWrite = File.OpenWrite(@"F:\MVC5_Demo\Project4YaSuo\Project4YaSuo\Files\yasuo.rar"))
{
//创建压缩流
using (GZipStream zipStream = new GZipStream(fsWrite, CompressionMode.Compress))
{
//每次读取1024byte
byte[] byts = new byte[ * ];
int len = ;
while ((len = fsRead.Read(byts, , byts.Length)) > )
{
zipStream.Write(byts, , len);//通过压缩流写入文件
}
}
}
}
}
压缩成rar文件
public void JieYa()
{
//读取压缩文件
using (FileStream fsRead = File.OpenRead(@"F:\MVC5_Demo\Project4YaSuo\Project4YaSuo\Files\yasuo.rar"))
{
//创建压缩流
using (GZipStream gzipStream = new GZipStream(fsRead, CompressionMode.Decompress))
{
using (FileStream fsWrite = File.OpenWrite(@"F:\MVC5_Demo\Project4YaSuo\Project4YaSuo\Files\笔记.txt"))
{
byte[] byts = new byte[ * ];
int len = ;
//写入新文件
while ((len = gzipStream.Read(byts, , byts.Length)) > )
{
fsWrite.Write(byts, , len);
}
} }
}
}
解压
C#文件压缩:ICSharpCode.SharpZipLib生成zip、tar、tar.gz的更多相关文章
- C# 文件压缩与解压(ZIP格式)
在企业开发过程中经常会遇到文件的压缩与解压,虽然网上很多流行的压缩文件格式都是RAR的,但是由于RAR不是一个开放的标准,因此ZIP成了更多人的选择.如果你不想自己开发的话可以选择开源的项目,比如Sh ...
- Java实现文件压缩与解压[zip格式,gzip格式]
Java实现ZIP的解压与压缩功能基本都是使用了Java的多肽和递归技术,可以对单个文件和任意级联文件夹进行压缩和解压,对于一些初学者来说是个很不错的实例. zip扮演着归档和压缩两个角色:gzip并 ...
- 将零散文件使用ICSharpCode.SharpZipLib压缩打包后一次性下载
public static Stream CreateZip(List<string> listPath, int level = 5) { MemoryStream mstream = ...
- Zip文件压缩(加密||非加密||压缩指定目录||压缩目录下的单个文件||根据路径压缩||根据流压缩)
1.写入Excel,并加密压缩.不保存文件 String dcxh = String.format("%03d", keyValue); String folderFileName ...
- linux 压缩解压命令zip、gz、tar.gz、bz2、tar.bz2、.tar.xz
linux压缩格式:.gz windows压缩格式:.zip .rar默认情况下,windows和linux都支持zip格式,都不需要安装额外软件. .zip格式 压缩zip /usr/bin/zip ...
- Linux使用——Linux命令——Linux文件压缩和解压使用记录
一:tar(可压缩可解压) tar命令是Unix/Linux系统中备份文件的可靠方法,几乎可以工作于任何环境中,它的使用权限是所有用户.但是tar本身只是一个文件打包工具,只有和其他工具组合时才具有压 ...
- linux中文件压缩介绍
原文内容来自于LZ(楼主)的印象笔记,如出现排版异常或图片丢失等问题,可查看当前链接:https://app.yinxiang.com/shard/s17/nl/19391737/1c62bb7f-f ...
- Linux之文件压缩与解压
文件压缩与解压 1.tar命令 tar命令可以为Linux的文件和目录创建档案. 利用tar,可以为某一特定文件创建档案(备份文件),也可以在档案中改变文件,或者向档案中加入新的文件.tar最初被用来 ...
- 利用ICSharpCode.SharpZipLib.Zip进行文件压缩
官网http://www.icsharpcode.net/ 支持文件和字符压缩. 创建全新的压缩包 第一步,创建压缩包 using ICSharpCode.SharpZipLib.Zip; ZipOu ...
随机推荐
- 分布式的几件小事(二)dubbo的工作原理
1.dubbo的工作原理 ①整体设计 图例说明: 图中左边淡蓝背景的为服务消费方使用的接口,右边淡绿色背景的为服务提供方使用的接口,位于中轴线上的为双方都用到的接口. 图中从下至上分为十层,各层均为单 ...
- Hadoop大数据平台入门——HDFS和MapReduce
随着硬件水平的不断提高,需要处理数据的大小也越来越大.大家都知道,现在大数据有多火爆,都认为21世纪是大数据的世纪.当然我也想打上时代的便车.所以今天来学习一下大数据存储和处理. 随着数据的不断变大, ...
- computed、watch、methods的区别
computed:计算属性是用来声明式的描述一个值依赖了其它的值.当你在模板里把数据绑定到一个计算属性上时,Vue 会在其依赖的任何值导致该计算属性改变时更新 DOM.这个功能非常强大,它可以让你的代 ...
- 第五篇 CSS入门 明白 三种嵌套形式,三种常用控制器
CSS入门 css是 层叠式样式表 css的作用是什么呢?举个抽象的例子啊,HTML是人,CSS则是衣服... css给html穿上衣服,有三种形式: 内嵌.内联.外联. 这三种形式,优先级为 ...
- 通用mapper将另外一个同名的表生成在同一个实体及mapper中
今天遇见了一个在网上都搜索不到的错误,使用通过mapper生成实体及mapper文件时会将另外一个数据库的同名文件生成在一个实体及mapper中,这样就会造成一个实体和mapper中有两个表的字段,经 ...
- 2019.10.9php进阶
<?php header("Content-type:text/html;charset:utf-8"); if ($_FILES["file"][&qu ...
- init container
init container与应用容器在本质上是一样的, 但它们是仅运行一次就结束的任务, 并且必须在成功执行完成后, 系统才能继续执行下一个容器, 可以用在例如应用容器启动前做一些初始化工作,当in ...
- jQuery获取当前按钮的id
function test(e) { $(e.target).attr('id') } // 记得带上点击事件
- 设置apache服务器的访问证书,支持https访问,windows
windows下载安装openssl http://slproweb.com/products/Win32OpenSSL.html windows证书的生成 安装成功后命令行执行 1.私钥,生成的文件 ...
- ZOJ3471Most Powerful(状态压缩)
问题 Recently, researchers on Mars have discovered N powerful atoms. All of them are different. These ...