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#压缩解压文件的更多相关文章

  1. 通过SharpZipLib来压缩解压文件

    在项目开发中,一些比较常用的功能就是压缩解压文件了,其实类似的方法有许多 ,现将通过第三方类库SharpZipLib来压缩解压文件的方法介绍如下,主要目的是方便以后自己阅读,当然可以帮到有需要的朋友更 ...

  2. .NET使用ICSharpCode.SharpZipLib压缩/解压文件

    SharpZipLib是国外开源加压解压库,可以方便的对文件进行加压/解压 1.下载ICSharpCode.SharpZipLib.dll,并复制到bin目录下 http://www.icsharpc ...

  3. huffman压缩解压文件【代码】

    距离上次写完哈夫曼编码已经过去一周了,这一周都在写huffman压缩解压,哎,在很多小错误上浪费了很多时间调bug.其实这个程序的最关键部分不是我自己想的,而是借鉴了某位园友的代码,但是,无论如何,自 ...

  4. 【转载】.NET压缩/解压文件/夹组件

    转自:http://www.cnblogs.com/asxinyu/archive/2013/03/05/2943696.html 阅读目录 1.前言 2.关于压缩格式和算法的基础 3.几种常见的.N ...

  5. C#使用SharpZipLib压缩解压文件

    #region 加压解压方法 /// <summary> /// 功能:压缩文件(暂时只压缩文件夹下一级目录中的文件,文件夹及其子级被忽略) /// </summary> // ...

  6. linux压缩解压文件

    首先进入文件夹 cd /home/ftp2/1520/web 压缩方法一:压缩web下的888.com网站 zip -r 888.com.zip888.com 压缩方法二:将当前目录下的所有文件和文件 ...

  7. Freebsd下压缩解压文件详解

    压缩篇: 把/usr/webgames目录下的文件打包.命名为bak.tar.gz 放到/usr/db-bak目录里 下面命令可以在任意目录执行.无视当前目录和将要存放文件的目录.tar -zcvf ...

  8. 跨平台的zip文件压缩处理,支持压缩解压文件夹

    根据minizip改写的模块,需要zlib支持 输出的接口: #define RG_ZIP_FILE_REPLACE 0 #define RG_ZIP_FILE_APPEND 1 //压缩文件夹目录, ...

  9. tar压缩解压文件

    查看visualization1.5.tar.gz 压缩包里面的内容: $ tar -tf visualization1.5.tar.gz 解压指定文件JavascriptVisualRelease/ ...

  10. Ubuntu下压缩解压文件

    一般来说ubuntu 下带有tar 命令,可以用来解压和压缩之用.但是我们经常要与win下用户打交道,所以要安装一些解压工具如:rar zip 等命令. 如果要需要用到zip工具那么可以: sudo ...

随机推荐

  1. AQS框架源码分析-AbstractQueuedSynchronizer

    前言:AQS框架在J.U.C中的地位不言而喻,可以说没有AQS就没有J.U.C包,可见其重要性,因此有必要对其原理进行详细深入的理解. 1.AQS是什么 在深入AQS之前,首先我们要搞清楚什么是AQS ...

  2. 专治编译器编辑器vscode中文乱码输出 win10 配置系统默认utf-8编码

    VS Code输出会出现乱码,很多人都遇到过.这是因为VS Code内部用的是utf-8编码,cmd/Powershell是gbk编码.直接编译,会把“你好”输出成“浣犲ソ”.如果把cmd的活动代码页 ...

  3. 压力测试Apache

    在做类似商城秒杀系统的同事都知道要在支持高并发,高可用的环境下进行多次的压力测试来防止自己的项目结构被高额的点击量击穿,导致商品超卖等损失 介绍一款简单的软件 xampp xam里带了Apache服务 ...

  4. 用 C# 编写 C# 编译器,先有鸡还是先有蛋?

    前段时间翻译了一篇文章 微软是如何重写 C# 编译器并使它开源的,文章讲了微软用 C# 重写 C# 编译器的坎坷路,引发了一些童鞋的思考:用 C# 编写 C# 编译器(Roslyn),那么 C# 编译 ...

  5. C# GDI+绘制一维条码打印模糊的解决办法

    最近遇到使用zxing生成的一维条码打印出来的条码图形很模糊根本识别不了.其实原因只有一句话: bitmap没有直接使用PrintDocument的Graphics画布进行绘制,而是中间处理了一下外部 ...

  6. windows服务器nginx+php启动开源ecshop

    1,下载php,nginx,ECShop源码 2,解压php到指定目录(如:C:\php-7.2.6) 2.1,找到指定目录下文件php.ini-development复制重命名为php.ini 2. ...

  7. Struts2拦截SQL注入

    <interceptors> <!--设置超时拦截器 --> <interceptor name="sessionOut" class="c ...

  8. IntentService+BroadcastReceiver 实现定时任务

    效果图: AlramIntentService package com.example.admin.water; import android.app.AlarmManager;import andr ...

  9. SpringMVC DispatcherServlet在配置Rest url-pattern的一点技巧

    SpringMVC的Controller中已经有了@RequestMapping(value = "detail.do", method = RequestMethod.GET)的 ...

  10. Linux 学习 (五) 压缩与解压缩命令

    Linux达人养成计划 I 学习笔记 常用压缩格式:.zip | .gz | .bz2 | .tar.gz | .tar.bz2 .zip zip 压缩文件名 源文件:压缩文件 zip -r 压缩文件 ...