网站首页
网站导航
Ctrl+D收藏
首 页
代码段
源码包
文档库
工具箱
代码语言
.
CSharp
.
JS
Java
Asp.Net
C
MSSQL
PHP
Css
PLSQL
Python
Shell
EBS
ASP
Perl
ObjC
VB.Net
VBS
MYSQL
GO
Delphi
AS
DB2
Domino
Rails
ActionScript
Scala
代码分类
文件
系统
字符串
数据库
网络相关
图形/GUI
多媒体
算法
游戏
Jquery
Extjs
Android
HTML5
菜单
网页交互
WinForm
控件
企业应用
安全与加密
脚本/批处理
开放平台
其它
【
C#
】
二进制转文件以及文件压缩和解压缩
作者:
明鑫
/ 发布于
2016/5/3
/
426
#region 将本地压缩文件转换为Base64编码 /// <summary> /// 将本地压缩文件转换为Base64编码 /// </summary> /// <returns></returns> public string ReturnBase64Code() { //从服务器获取到的文件路径 string ys_filePath = rootDirectoryPath + @"\hx.zip"; //将压缩文件转换为二进制 using (FileStream fs = new FileStream(ys_filePath, FileMode.Open)) { byte[] bytes = new byte[fs.Length]; int count = Convert.ToInt32(fs.Length); fs.Read(bytes, 0, count); fs.Close(); //将二进制转为为base64 return Convert.ToBase64String(bytes); } } #endregion #region 直接删除指定目录下的所有文件及文件夹(保留目录) /// <summary> /// 直接删除指定目录下的所有文件及文件夹(保留目录) /// </summary> /// <param name="strPath">文件夹路径</param> /// <returns>执行结果</returns> public bool DeleteDir(string strPath) { try { strPath = @strPath.Trim().ToString();// 清除空格 if (System.IO.Directory.Exists(strPath)) // 判断文件夹是否存在 { // 获得文件夹数组 string[] strDirs = System.IO.Directory.GetDirectories(strPath); // 获得文件数组 string[] strFiles = System.IO.Directory.GetFiles(strPath); // 遍历所有子文件夹 foreach (string strFile in strFiles) { // 删除文件夹 System.IO.File.Delete(strFile); } // 遍历所有文件 foreach (string strdir in strDirs) { // 删除文件 System.IO.Directory.Delete(strdir, true); } } return true; } catch (Exception Exp) // 异常处理 { System.Diagnostics.Debug.Write(Exp.Message.ToString()); // 异常信息 return false; } } #endregion #region 定时下载广告文件 public void theout(object source, System.Timers.ElapsedEventArgs e) { string str = ReturnBase64Code();//将二进制转为为base64 byte[] outputb = Convert.FromBase64String(str);//将base64编码转换为二进制 //将二进制转换为压缩文件 string path = rootDirectoryPath + @"\new_hx.zip";//压缩文件的地址 File.WriteAllBytes(path, outputb); //删除广告目录下已经存在的文件 if (Directory.Exists(filePath)) { DeleteDir(filePath); } //解压文件 bool result = bonkerZip.UnZipFile(path, filePath); // DeCompressionZip if (!result) { ErrorLog.WriteErrorLog(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "广告文件解压失败,失败原因:"+bonkerZip.errorMsg); } webBrowser1.Navigate(filePath+@"\index.html"); } #endregion public class BonkerZip { /// <summary> /// 存放待压缩的文件的绝对路径 /// </summary> private List<string> AbsolutePaths { set; get; } public string errorMsg { set; get; } public BonkerZip() { errorMsg = ""; AbsolutePaths = new List<string>(); } /// <summary> /// 添加压缩文件 /// </summary> /// <param name="_fileAbsolutePath">文件的绝对路径</param> public void AddFile(string _fileAbsolutePath) { AbsolutePaths.Add(_fileAbsolutePath); } /// <summary> /// 压缩文件或者文件夹 /// </summary> /// <param name="_depositPath">压缩后文件的存放路径 如C:\\windows\abc.zip</param> /// <returns></returns> public bool CompressionZip(string _depositPath) { bool result = true; FileStream fs = null; try { ZipOutputStream ComStream = new ZipOutputStream(File.Create(_depositPath)); ComStream.SetLevel(9); //压缩等级 foreach (string path in AbsolutePaths) { //如果是目录 if (Directory.Exists(path)) { ZipFloder(path, ComStream, path); } else if (File.Exists(path))//如果是文件 { fs = File.OpenRead(path); byte[] bts = new byte[fs.Length]; fs.Read(bts, 0, bts.Length); ZipEntry ze = new ZipEntry(new FileInfo(path).Name); ComStream.PutNextEntry(ze); //为压缩文件流提供一个容器 ComStream.Write(bts, 0, bts.Length); //写入字节 } } ComStream.Finish(); // 结束压缩 ComStream.Close(); } catch (Exception ex) { if (fs != null) { fs.Close(); } errorMsg = ex.Message; result = false; } return result; } //压缩文件夹 private void ZipFloder(string _OfloderPath, ZipOutputStream zos, string _floderPath) { foreach (FileSystemInfo item in new DirectoryInfo(_floderPath).GetFileSystemInfos()) { if (Directory.Exists(item.FullName)) { ZipFloder(_OfloderPath, zos, item.FullName); } else if (File.Exists(item.FullName))//如果是文件 { DirectoryInfo ODir = new DirectoryInfo(_OfloderPath); string fullName2 = new FileInfo(item.FullName).FullName; string path = ODir.Name + fullName2.Substring(ODir.FullName.Length, fullName2.Length - ODir.FullName.Length);//获取相对目录 FileStream fs = File.OpenRead(fullName2); byte[] bts = new byte[fs.Length]; fs.Read(bts, 0, bts.Length); ZipEntry ze = new ZipEntry(path); zos.PutNextEntry(ze); //为压缩文件流提供一个容器 zos.Write(bts, 0, bts.Length); //写入字节 } } } /// <summary> /// 解压 /// </summary> /// <param name="_depositPath">压缩文件路径</param> /// <param name="_floderPath">解压的路径</param> /// <returns></returns> public bool DeCompressionZip(string _depositPath, string _floderPath) { bool result = true; FileStream fs=null; try { using (ZipInputStream InpStream = new ZipInputStream(File.OpenRead(_depositPath))) { ZipEntry ze = InpStream.GetNextEntry();//获取压缩文件中的每一个文件 Directory.CreateDirectory(_floderPath);//创建解压文件夹 while (ze != null)//如果解压完ze则是null { if (ze.IsFile)//压缩zipINputStream里面存的都是文件。带文件夹的文件名字是文件夹\\文件名 { string[] strs = ze.Name.Split('\\');//如果文件名中包含’\\‘则表明有文件夹 if (strs.Length > 1) { //两层循环用于一层一层创建文件夹 for (int i = 0; i < strs.Length - 1; i++) { string floderPath = _floderPath; for (int j = 0; j < i; j++) { floderPath = floderPath + "\\" + strs[j]; } floderPath = floderPath + "\\" + strs[i]; Directory.CreateDirectory(floderPath); } } fs = new FileStream(_floderPath + "\\" + ze.Name, FileMode.OpenOrCreate, FileAccess.Write);//创建文件 //循环读取文件到文件流中 while (true) { byte[] bts = new byte[1024]; int i = InpStream.Read(bts, 0, bts.Length); if (i > 0) { fs.Write(bts, 0, i); } else { fs.Flush(); fs.Close(); break; } } } ze = InpStream.GetNextEntry(); } } } catch (Exception ex) { if (fs != null) { fs.Close(); } errorMsg = ex.Message; result = false; } finally { if (fs != null) { fs.Close(); fs.Dispose(); } } return result; } /// <summary> /// 功能:解压zip格式的文件。 /// </summary> /// <param name="zipFilePath">压缩文件路径</param> /// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param> /// <param name="err">出错信息</param> /// <returns>解压是否成功</returns> public bool UnZipFile(string zipFilePath, string unZipDir)// , out string err { // err = ""; if (zipFilePath == string.Empty) { //err = "压缩文件不能为空!"; return false; } if (!File.Exists(zipFilePath)) { //err = "压缩文件不存在!"; return false; } //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹 if (unZipDir == string.Empty) unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath)); if (!unZipDir.EndsWith("\\")) unZipDir += "\\"; if (!Directory.Exists(unZipDir)) Directory.CreateDirectory(unZipDir); try { using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath.ToLower()))) { ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { string directoryName = Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); if (directoryName.Length > 0) { Directory.CreateDirectory(unZipDir + directoryName); } if (!directoryName.EndsWith("\\")) directoryName += "\\"; if (fileName != String.Empty) { using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name)) { int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } } } }//while } } catch (Exception ex) { //err = ex.Message; return false; } return true; }//解压结束 }
评论列表
本站所提供的代码,版权归原作者所有,若有侵犯作者版权,请与我们联系,我们将立即删除或修改。谢谢!
本站所有代码发布及提供者。
试试其它关键字
同语言下
.
C#动态修改文件夹名称(FSO实现,不移动文件)
.
c# 移动文件或文件夹
.
c#图片添加水印
.
网站后台修改图片尺寸代码
.
处理大图片在缩略图时的展示
.
实现对图片上传的接收
.
去除字符串中的空格,回车,换行符转变成‘;’在按‘
.
按照回车换行符分割字符串
.
文件MD5码 比较,检测文件是否一样
.
计算每周和每月固定日期
可能有用的
.
C#动态修改文件夹名称(FSO实现,不移动文件)
.
c# 移动文件或文件夹
.
c#图片添加水印
.
网站后台修改图片尺寸代码
.
处理大图片在缩略图时的展示
.
实现对图片上传的接收
.
去除字符串中的空格,回车,换行符转变成‘;’在按‘
.
按照回车换行符分割字符串
.
文件MD5码 比较,检测文件是否一样
.
计算每周和每月固定日期
明鑫
贡献的其它代码
(
17
)
.
监测Nginx访问日志502情况,并做相应动作
.
String 去除空格 回车 换行 水平制表符
.
进程相关
.
基于php的加油卡充值接口调用代码实例
.
遍历CookieContainer所有Cookie并保存到文件
.
基于JDBC的数据库DAO封装
.
js设置选中的行样式
.
js设置选中的行样式
.
curl下载文件到本地服务器
.
div上下居中css
地图
本站
我们
服务
版权
联系
回馈
博客