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[5]; int nRead = stream.Read(bom, offset: 0, count: 5); if (bom[0] == 0xff && bom[1] == 0xfe && bom[2] == 0 && bom[3] == 0) { WriteLine("UTF-32"); stream.Seek(4, SeekOrigin.Begin); return Encoding.UTF32; } else if(bom[0] == 0xff && bom[1] == 0xfe) { WriteLine("UFT-16, little endian"); stream.Seek(2, SeekOrigin.Begin); return Encoding.Unicode; } else if (bom[0] == 0xfe && bom[1] == 0xff) { WriteLine("UTF-16, big endian"); stream.Seek(2, SeekOrigin.Begin); return Encoding.BigEndianUnicode; } //UTF-8是Unicode的实现方式之一。(可变长度字符编码) else if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) { WriteLine("UTF-8"); stream.Seek(3, SeekOrigin.Begin); return Encoding.UTF8; } stream.Seek(0, SeekOrigin.Begin); return encoding; } public static void ReadFileUsingFileStream(string fileName) { const int bufferSize = 1024; 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, 0, bufferSize); if (nRead == 0) completed = true; if (nRead < bufferSize) { Array.Clear(buffer, nRead, bufferSize - nRead); } string s = encoding.GetString(buffer, 0, 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 = 1000;//指定超时时间 stream.WriteTimeout = 1000; } } 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, 0, preamble.Length); string hello = "Hello, World!"; byte[] buffer = Encoding.UTF8.GetBytes(hello); stream.Write(buffer, 0, 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(0, SeekOrigin.Begin); using (var reader = new StreamReader(outputStream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 4096, 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}"); } } }