C#压缩解压文件
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;
using static System.Console; //使用流处理文件
//FileStream //读取器和写入器
//StreamReader StreamWriter //读写二进制文件
//BinaryReader BinaryWriter //压缩流
//使用DeflateStream和GZipStream来压缩和解压缩流
//它们使用同样的压缩算法,GZipStream在后台使用DeflateStream,增加了校验 //ZipArchive类可以创建和读取ZIP文件 //添加引用System.IO.Compression.dll, System.IO.Compression.FileSystem.dll
//Windows资源管理器可以直接打开ZipArchive,但不能打开GZipStream压缩的文件 //观察文件的更改
//FileSystemWatcher namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
//文件流
string fileName = "D:\\1.txt";
//using语句会自动调用(即使发生错误)该变量的Dispose()释放资源
using (var stream = new FileStream(fileName, FileMode.Open,
FileAccess.Read, FileShare.Read))
//FileStream stream1 = File.OpenRead(fileName);
{
//ShowStreamInfo(stream);
//GetEncoding(stream);
} ReadFileUsingFileStream(fileName); //WriteTextFile(); //压缩文件
CompressFile(fileName, "D:\\1.z");
//解压缩
DecompressFile("D:\\1.z"); //压缩文件
CreateZipFile("D:\\1", "D:\\1.zip"); //观察文件的更改
string path = "d:\\1";
string filter = "*.txt";//目录下所有txt文件
var watcher = new FileSystemWatcher(path, filter) { IncludeSubdirectories = true };
watcher.Created += OnFileChanged;
watcher.Changed += OnFileChanged;
watcher.Deleted += OnFileChanged;
watcher.Renamed += OnFileRenamed; watcher.EnableRaisingEvents = true;
WriteLine("watching file changes..."); ReadKey();
} private static Encoding GetEncoding(Stream stream)
{
if (!stream.CanSeek)
throw new ArgumentException("require a stream that can seek");
Encoding encoding = Encoding.ASCII; byte[] bom = new byte[];
int nRead = stream.Read(bom, offset: , count: );
if (bom[] == 0xff && bom[] == 0xfe && bom[] == && bom[] == )
{
WriteLine("UTF-32");
stream.Seek(, SeekOrigin.Begin);
return Encoding.UTF32;
}
else if(bom[] == 0xff && bom[] == 0xfe)
{
WriteLine("UFT-16, little endian");
stream.Seek(, SeekOrigin.Begin);
return Encoding.Unicode;
}
else if (bom[] == 0xfe && bom[] == 0xff)
{
WriteLine("UTF-16, big endian");
stream.Seek(, SeekOrigin.Begin);
return Encoding.BigEndianUnicode;
}
//UTF-8是Unicode的实现方式之一。(可变长度字符编码)
else if (bom[] == 0xef && bom[] == 0xbb && bom[] == 0xbf)
{
WriteLine("UTF-8");
stream.Seek(, SeekOrigin.Begin);
return Encoding.UTF8;
} stream.Seek(, SeekOrigin.Begin);
return encoding;
} public static void ReadFileUsingFileStream(string fileName)
{
const int bufferSize = ;
using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
ShowStreamInfo(stream);
Encoding encoding = GetEncoding(stream);
byte[] buffer = new byte[bufferSize];
bool completed = false;
do
{
int nRead = stream.Read(buffer, , bufferSize);
if (nRead == )
completed = true;
if (nRead < bufferSize)
{
Array.Clear(buffer, nRead, bufferSize - nRead);
} string s = encoding.GetString(buffer, , nRead);
WriteLine($"read {nRead} bytes");
WriteLine(s);
} while (!completed);
}
} public static void ShowStreamInfo(FileStream stream)
{
WriteLine(stream.CanRead);
WriteLine(stream.CanWrite);
WriteLine(stream.CanSeek);
WriteLine(stream.CanTimeout);
WriteLine(stream.Position);
WriteLine(stream.Length); if (stream.CanTimeout)
{
WriteLine(stream.ReadTimeout);
WriteLine(stream.WriteTimeout);
stream.ReadTimeout = ;//指定超时时间
stream.WriteTimeout = ;
}
} public static void WriteTextFile()
{
string tempTextFileName = Path.ChangeExtension(Path.GetTempFileName(), "txt");
using (FileStream stream = File.OpenWrite(tempTextFileName))
{
////UTF-8
//stream.WriteByte(0xef);
//stream.WriteByte(0xbb);
//stream.WriteByte(0xbf); //或
byte[] preamble = Encoding.UTF8.GetPreamble();
stream.Write(preamble, , preamble.Length); string hello = "Hello, World!";
byte[] buffer = Encoding.UTF8.GetBytes(hello);
stream.Write(buffer, , buffer.Length);
WriteLine($"file{stream.Name} written");
}
} public static void CompressFile(string fileName, string compressedFileName)
{
using (FileStream inputStream = File.OpenRead(fileName))
{
FileStream outputStream = File.OpenWrite(compressedFileName); using (var compressStream =
new DeflateStream(outputStream, CompressionMode.Compress))
{
inputStream.CopyTo(compressStream);
}
} } public static void DecompressFile(string compressedFileName)
{
FileStream inputStream = File.OpenRead(compressedFileName); using (MemoryStream outputStream = new MemoryStream())
using (var compressStream = new DeflateStream(inputStream,
CompressionMode.Decompress))
{
compressStream.CopyTo(outputStream);
outputStream.Seek(, SeekOrigin.Begin);
using (var reader = new StreamReader(outputStream, Encoding.UTF8,
detectEncodingFromByteOrderMarks: true, bufferSize: , leaveOpen: true))
{
string result = reader.ReadToEnd();
WriteLine(result);
}
}
} public static void CreateZipFile(string directory, string zipFile)
{
FileStream zipStream = File.OpenWrite(zipFile);
using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Create))
{
if (File.Exists(directory))
{
ZipArchiveEntry entry = archive.CreateEntry(Path.GetFileName(directory));
using (FileStream inputStream = File.OpenRead(directory))
using (Stream outputStream = entry.Open())
{
inputStream.CopyTo(outputStream);
}
}
else
{
//此方法不能压缩文件夹
IEnumerable<string> files = Directory.EnumerateFiles(directory, "*",
SearchOption.TopDirectoryOnly);
foreach (var file in files)
{
ZipArchiveEntry entry = archive.CreateEntry(Path.GetFileName(file));
using (FileStream inputStream = File.OpenRead(file))
using (Stream outputStream = entry.Open())
{
inputStream.CopyTo(outputStream);
}
}
}
}
} private static void OnFileChanged(object sender, FileSystemEventArgs e)
{
WriteLine($"file {e.Name} {e.ChangeType}");
} private static void OnFileRenamed(object sender, RenamedEventArgs e)
{
WriteLine($"file {e.OldName} {e.ChangeType} to {e.Name}");
}
}
}
C#压缩解压文件的更多相关文章
- 通过SharpZipLib来压缩解压文件
在项目开发中,一些比较常用的功能就是压缩解压文件了,其实类似的方法有许多 ,现将通过第三方类库SharpZipLib来压缩解压文件的方法介绍如下,主要目的是方便以后自己阅读,当然可以帮到有需要的朋友更 ...
- .NET使用ICSharpCode.SharpZipLib压缩/解压文件
SharpZipLib是国外开源加压解压库,可以方便的对文件进行加压/解压 1.下载ICSharpCode.SharpZipLib.dll,并复制到bin目录下 http://www.icsharpc ...
- huffman压缩解压文件【代码】
距离上次写完哈夫曼编码已经过去一周了,这一周都在写huffman压缩解压,哎,在很多小错误上浪费了很多时间调bug.其实这个程序的最关键部分不是我自己想的,而是借鉴了某位园友的代码,但是,无论如何,自 ...
- 【转载】.NET压缩/解压文件/夹组件
转自:http://www.cnblogs.com/asxinyu/archive/2013/03/05/2943696.html 阅读目录 1.前言 2.关于压缩格式和算法的基础 3.几种常见的.N ...
- C#使用SharpZipLib压缩解压文件
#region 加压解压方法 /// <summary> /// 功能:压缩文件(暂时只压缩文件夹下一级目录中的文件,文件夹及其子级被忽略) /// </summary> // ...
- linux压缩解压文件
首先进入文件夹 cd /home/ftp2/1520/web 压缩方法一:压缩web下的888.com网站 zip -r 888.com.zip888.com 压缩方法二:将当前目录下的所有文件和文件 ...
- Freebsd下压缩解压文件详解
压缩篇: 把/usr/webgames目录下的文件打包.命名为bak.tar.gz 放到/usr/db-bak目录里 下面命令可以在任意目录执行.无视当前目录和将要存放文件的目录.tar -zcvf ...
- 跨平台的zip文件压缩处理,支持压缩解压文件夹
根据minizip改写的模块,需要zlib支持 输出的接口: #define RG_ZIP_FILE_REPLACE 0 #define RG_ZIP_FILE_APPEND 1 //压缩文件夹目录, ...
- tar压缩解压文件
查看visualization1.5.tar.gz 压缩包里面的内容: $ tar -tf visualization1.5.tar.gz 解压指定文件JavascriptVisualRelease/ ...
- Ubuntu下压缩解压文件
一般来说ubuntu 下带有tar 命令,可以用来解压和压缩之用.但是我们经常要与win下用户打交道,所以要安装一些解压工具如:rar zip 等命令. 如果要需要用到zip工具那么可以: sudo ...
随机推荐
- Python 隔离环境 virtualenv
1) 安装 $ sudo pip3 install virtualenv 2) 创建并进入工程目录,例如 myproject $ mkdir myproject $ cd myproject 3) 在 ...
- i春秋 百度杯”CTF比赛 十月场 login
出现敏感的信息,然后进行登录 登录成功发现奇怪的show 然后把show放到发包里面试一下 出现了源码,审计代码开始 出flag的条件要user 等于春秋 然后进行login来源于反序列化后的logi ...
- Linux笔记-nohup和&
nohup:忽略SIGHUP信号,当关闭shell之后,程序仍然执行,但是如果在shell中 ctrl+c,会结束程序 &:忽略SIGINT信号,程序后台执行,在shell中 ctrl+c,程 ...
- Sublime 禁止自动升级
打开SUblime Prefreences 找到"设置-用户" 添加 "update_check":false, 即可禁用默认升级 此时完整如下 { &q ...
- Python--day03(变量、数据类型、运算符)
day02主要内容回顾 1.语言的分类 -- 机器语言:直接编写0,1指令,直接能被硬件执行 -- 汇编语言:编写助记符(与指令的对应关系),找到对应的指令直接交给硬件执行 -- 高级语言:编写人能识 ...
- Android艺术——探究Handler运行机制
我们从开发的角度来说,Handler是Android 的消息机制的上层接口.说到Handler,大家都会说:哦,Handler这个我知道干什么的,更新UI.没错,Handler的确是用于更新UI的,具 ...
- Vue.Draggable
Vue.Draggable拖动效果 下载包:npm install vue-draggable --save 组件中引进依赖: import draggable from 'vuedraggable' ...
- android O 打开设置->声音->“点按时震动问题”
主要原因是和导航栏和屏幕最下方3个按键的属性配置有关,因为在PhoneWindowManager中调用方法performHapticFeedbackLw(null, HapticFeedbackCon ...
- java9最新发布
链接:http://pan.baidu.com/s/1slbRFa9 密码:hcdj 给大家分享可以去下载 已接受的特性 1. Jigsaw 项目:模块化JDK源码 Jigsaw项目即JEP201是为 ...
- 20175221 《Java程序设计》第5周学习总结
20175221 <Java程序设计>第5周学习总结 教材学习内容总结 接口的定义 接口声明:interface 接口名 接口体中只可以有常量,而没有变量 接口体中只有抽象方法(可省略 ...