using (FileStream reader=new FileStream (@"c:\1.txt",FileMode.Open,FileAccess.Read)) { using (FileStream writer=new FileStream (@"c:\4.zp",FileMode.OpenOrCreate,FileAccess.Write)) { //壓縮寫的流 using (GZipStream zip=new GZipStream (writer,CompressionMode.Compress)) { byte[] buffer = new byte[12]; int r = 0; while ((r=reader.Read(buffer,0,buffer.Length))>0) { //壓縮寫入 zip.Write(buffer,0,r); } } } } Console.WriteLine("/壓縮完成"); using (FileStream reader = new FileStream(@"c:\4.zp", FileMode.OpenOrCreate, FileAccess.Read)) { using (FileStream writer = new FileStream(@"c:\5.txt", FileMode.OpenOrCreate, FileAccess.Write)) { byte[] buffer = new byte[13]; //解壓讀的流 因讀的是壓縮文件,reader讀出的是壓縮後的流 using (GZipStream zip = new GZipStream(reader, CompressionMode.Decompress)) { int r=0; while ((r = zip.Read(buffer, 0, buffer.Length)) > 0) { //正常的流寫入 writer.Write(buffer, 0, r); } } } }
這種壓縮只能實現單個文件的壓縮和解壓,多個文件的暫時不能使用spa