閑談.NET Framework Compression功能應(yīng)用技巧
.NET Framework能為開發(fā)人員提供一個(gè)合適的WEB應(yīng)用程序部署平臺(tái),幫助他們輕松的完成各種程序的開發(fā)創(chuàng)建。以前做項(xiàng)目的時(shí)候,需要提供文件壓縮功能。當(dāng)時(shí)是使用了一個(gè)開源的類庫(kù),名為ZipLib,使用起來還是很方便的。在.Net 2.0中,微軟在System.IO中新增了System.IO.Compression命名空間,.NET Framework Compression功能提供了壓縮功能的相關(guān)類GZipStream。 #t#
這個(gè)類的使用與一般的文件流使用差不多。我沒有分析其內(nèi)部實(shí)現(xiàn),但猜測(cè)應(yīng)該還是采用Decorator模式對(duì)Stream進(jìn)行了裝飾,從中應(yīng)用了.NET Framework Compression功能的算法。它通過Write()方法,將buffer里面的內(nèi)容寫到另一個(gè)文件流中,例如源文件為sourceFile,壓縮后的文件為targetFile,則方法為:
- byte[] buffer = null;
- FileStream sourceStream = null;
- FileStream targetStream = null;
- GZipStream compressedStream = null;
- sourceStream = new FileStream
(sourceFile,FileMode.Open,FileAccess.
Read,FileShare.Read); - buffer = new byte[sourceStream.Length];
- sourceStream.Read(buffer,0,buffer.Length);
- targetStream = new FileStream
(targetFile,FileMode.OpenOrCreate,
FileAccess.Write); - //將CompressedStream指向targetStream;
- compressedStream = new GZipStream
(targetStream,CompressionMode.
Compress,true); - compressStream.Write(buffer,0,
buffer.Length);
在使用GZipStream時(shí),需要添加引用:
- using System.IO;
- using System.IO.Compression;
.NET Framework Compression功能的解壓縮與前面的方法差不多,仍然使用GZipStream文件流:
- // Read in the compressed source stream
- sourceStream = new FileStream
( sourceFile, FileMode.Open );- // Create a compression stream pointing
to the destiantion stream- decompressedStream = new GZipStream
( sourceStream, CompressionMode.
Decompress, true );- // Read the footer to determine the
length of the destiantion file- quartetBuffer = new byte[4];
- int position = (int)sourceStream.Length - 4;
- sourceStream.Position = position;
- sourceStream.Read ( quartetBuffer, 0, 4 );
- sourceStream.Position = 0;
- int checkLength = BitConverter.ToInt32
( quartetBuffer, 0 );- byte[] buffer = new byte[checkLength + 100];
- int offset = 0;
- int total = 0;
- // Read the compressed data into the buffer
- while ( true )
- {
- int bytesRead = decompressedStream.Read
( buffer, offset, 100 );- if ( bytesRead == 0 ) break;
- offset += bytesRead; total += bytesRead;
- }
- // Now write everything to the destination file
- destinationStream = new FileStream
( destinationFile, FileMode.Create );- destinationStream.Write ( buffer, 0, total );
- // and flush everyhting to clean out the buffer
- destinationStream.Flush ( );
怎么樣,通過對(duì).NET Framework Compression功能的介紹,大家應(yīng)該基本掌握了其中的應(yīng)用技巧了吧。