博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
CSharp tar类型文件压缩与解压
阅读量:6070 次
发布时间:2019-06-20

本文共 6436 字,大约阅读时间需要 21 分钟。

 

最近闲暇时间开始写点通用基础类在写到tar类型文件压缩与解压时遇到点问题

 

压缩用的类库我是下载的 SharpZipLib_0860版本

先上代码

加压核心

 

/// 		/// 内部文件及文件夹压缩方法		/// 		/// 被压缩的文件及文件夹路径		/// tar压缩文件流		/// 压缩文件流基于的根路径		private void AddCompressFileAndFolders(string[] paths, TarOutputStream outputStream, string basePath, int compression)		{			try			{				foreach (string path in paths)				{					TarEntry entry = null;					if (FolderProvider.IsFolder(path))					{						if (string.IsNullOrEmpty(basePath))							basePath = FolderProvider.GetSuperFolderPath(path);						//is directory						string[] subFileAndFolders = FolderProvider.GetAllContainsFileAndFolderPaths(path);						TarHeader header = new TarHeader();						header.Name = path.Replace(basePath + "\\", string.Empty) + "\\";						header.Mode = compression;						entry = new TarEntry(header);						if (subFileAndFolders.Length == 0)						{							outputStream.PutNextEntry(entry);							outputStream.CloseEntry();						}						/*当前路径为子路径的父路径*/						AddCompressFileAndFolders(subFileAndFolders, outputStream, basePath, compression);					}					else					{						//is file						using (FileStream file = System.IO.File.OpenRead(path))						{							string filePath = path;							if (!string.IsNullOrEmpty(basePath))							{								filePath = path.Replace(basePath + "\\", string.Empty);							}							else							{								filePath = Path.GetFileName(path);							}							byte[] buffer = new byte[1024 * 1024 * 4];							int size = 1;							TarHeader header = new TarHeader();							header.Name = filePath;							header.ModTime = DateTime.Now;							header.Size = file.Length;							entry = new TarEntry(header);							outputStream.PutNextEntry(entry);							while (size > 0)							{								size = file.Read(buffer, 0, buffer.Length);								if (size == 0)									break;								outputStream.Write(buffer, 0, size);							}							outputStream.CloseEntry();						}					}				}			}			catch (Exception ex)			{				throw ex;			}		}

 

解压核心

 

/// 		/// 功能:解压tar格式的文件。		/// 		/// 压缩文件路径		/// 解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹		/// 密码		/// 
解压是否成功
public bool UnCompressFile(string zipFilePath, string unZipDir = null, string password = null) { if (zipFilePath == string.Empty) { throw new Exception("压缩文件不能为空!"); } if (!System.IO.File.Exists(zipFilePath)) { throw new Exception("压缩文件不存在!"); } //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹 if (string.IsNullOrEmpty(unZipDir)) unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath)); if (!unZipDir.EndsWith("\\")) unZipDir += "\\"; if (!Directory.Exists(unZipDir)) FolderProvider.CreateDirectory(unZipDir); try { using (TarInputStream input = new TarInputStream(System.IO.File.OpenRead(zipFilePath))) { //if (!string.IsNullOrEmpty(password)) input.Password = password; TarEntry theEntry; while ((theEntry = input.GetNextEntry()) != null) { string directoryName = Path.GetDirectoryName(theEntry.Name); //string fileName = Path.GetFileName(Encoding.UTF8.GetString(theEntry.Name)); string fileName = Path.GetFileName(theEntry.Name); if (directoryName.Length > 0) { Directory.CreateDirectory(unZipDir + directoryName); } if (!directoryName.EndsWith("\\")) directoryName += "\\"; if (fileName != String.Empty) { // Because the uncompressed size of the file is unknown, // we are using an arbitrary buffer size. byte[] buffer = new byte[1024 * 1024 * 4]; int size = buffer.Length; using (FileStream streamWriter = System.IO.File.Create(unZipDir + theEntry.Name)) { while (size > 0) { size = input.Read(buffer, 0, buffer.Length); if (size == 0) break; streamWriter.Write(buffer, 0, size); } } } }//while } } catch (Exception ex) { throw ex; } return true; }//解压结束

遇到的问题是

 

1,中文乱码,

2 压缩文件中的空文件夹下多了个不知道是没有没名称的文件夹还是没有名称及后缀名的文件但是用解压方法解压或是解压工具解压后确实是空文件夹

中文乱码的解决:

根据问题应该是在字符与byte转换时没有指点Encoding造成的, 下载SharpZipLib_0860_SourceSamples.zip,源码查看

先调整加压函数,修个TarHeader文件里的下面的函数,下面是修正后的

 

/// 		/// Add 
name
to the buffer as a collection of bytes ///
/// The name to add /// The offset of the first character /// The buffer to add to /// The index of the first byte to add /// The number of characters/bytes to add ///
The next free index in the
public static int GetNameBytes(string name, int nameOffset, byte[] buffer, int bufferOffset, int length) { if (name == null) { throw new ArgumentNullException("name"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } int i; ///解决tar压缩中文乱码问题 byte[] arrName = Encoding.GetEncoding(Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage).GetBytes(name); for (i = 0; i < length - 1 && nameOffset + i < arrName.Length; ++i) { buffer[bufferOffset + i] = (byte)arrName[nameOffset + i]; } for (; i < length; ++i) { buffer[bufferOffset + i] = 0; } return bufferOffset + length; }

编译后调用,运行单元测试,压缩文件中中文显示正常,运行解压测试,解压后依旧乱码,

 

继续调整TarHeader文件中的函数,调整后如下:

 

/// 		/// Parse a name from a header buffer.		/// 		/// 		/// The header buffer from which to parse.		/// 		/// 		/// The offset into the buffer from which to parse.		/// 		/// 		/// The number of header bytes to parse.		/// 		/// 
/// The name parsed. ///
static public StringBuilder ParseName(byte[] header, int offset, int length) { if (header == null) { throw new ArgumentNullException("header"); } if (offset < 0) {#if NETCF_1_0 throw new ArgumentOutOfRangeException("offset");#else throw new ArgumentOutOfRangeException("offset", "Cannot be less than zero");#endif } if (length < 0) {#if NETCF_1_0 throw new ArgumentOutOfRangeException("length");#else throw new ArgumentOutOfRangeException("length", "Cannot be less than zero");#endif } if (offset + length > header.Length) { throw new ArgumentException("Exceeds header size", "length"); } StringBuilder result = new StringBuilder(length); List
temp = new List
(); for (int i = offset; i < offset + length; ++i) { if (header[i] == 0) { break; } //result.Append((char)header[i]); temp.Add(header[i]); } result.Append(Encoding.GetEncoding(Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage).GetString(temp.ToArray())); return result; }

之前说的第二个问题还没解决,希望有哪位大侠解决了告诉我一下,多谢

 

 

转载地址:http://ogygx.baihongyu.com/

你可能感兴趣的文章
有关于key值
查看>>
MyEclipse10中导入的jquery文件报错(出现红叉叉,提示语法错误)
查看>>
cursor:not-allowed
查看>>
检验函数运行时间
查看>>
【转】Objective-C学习笔记八:类的定义二
查看>>
算法19-----(位运算)找出数组中出现只出现一次的数
查看>>
linux 系统shell运行程序不退出
查看>>
【BZOJ2019】nim
查看>>
MySQL之高可用MHA部署
查看>>
Oracle临时表空间满了的解决办法
查看>>
springboot~Profile开发环境与单元测试用不同的数据库
查看>>
SQL 截取时间
查看>>
Jquery 特效 图片轮转 菜单
查看>>
Vue全局添加组件或者模块
查看>>
Odoo 开源微信小程序商城模块
查看>>
多选插件multiselect.js
查看>>
img图片不存在显示默认图
查看>>
Struts07---访问servlet的API
查看>>
Lehman Brothers NY面经
查看>>
企业高并发的成熟解决方案(一)video(笔记&知识点)
查看>>