C#壓縮和解壓縮字節(GZip)

標題:C#壓縮和解壓縮字節(GZip的使用)

做用:此類在 .NET Framework 2.0 版中是新增的。提供用於壓縮和解壓縮流的方法和屬性。
定義:表示 GZip 數據格式,它使用無損壓縮和解壓縮文件的行業標準算法。這種格式包括一個檢測數據損壞的循環冗餘校驗值。GZip 數據格式使用的算法與 DeflateStream 類的算法相同,但它能夠擴展以使用其餘壓縮格式。這種格式能夠經過不涉及專利使用權的方式輕鬆實現。gzip 的格式能夠從 RFC 1952「GZIP file format specification 4.3(GZIP 文件格式規範 4.3)GZIP file format specification 4.3(GZIP 文件格式規範 4.3)」中得到。此類不能用於壓縮大於 4 GB 的文件。算法


下面給出兩個具體Demo:
實例1數組

//壓縮字節
//1.建立壓縮的數據流 
//2.設定compressStream爲存放被壓縮的文件流,並設定爲壓縮模式
//3.將須要壓縮的字節寫到被壓縮的文件流
public static byte[] CompressBytes(byte[] bytes)
{
    using(MemoryStream compressStream = new MemoryStream())
    {
        using(var zipStream = new GZipStream(compressStream, CompressMode.ComPress))
            zipStream.Write(bytes, 0, bytes.Length);
        return compressStream.ToArray();
    }
}
//解壓縮字節
//1.建立被壓縮的數據流
//2.建立zipStream對象,並傳入解壓的文件流
//3.建立目標流
//4.zipStream拷貝到目標流
//5.返回目標流輸出字節
public static byte[] Decompress(byte[] bytes)
{
    using(var compressStream = new MemoryStream(bytes))
    {
        using(var zipStream = new GZipStream(compressStream, CompressMode.DeCompress))
        {
            using(var resultStream = new MemoryStream())
            {
                zipStream.CopyTo(resultStream);
                return resultStream.ToArray();
            }
        }
    }
}

實例2(摘自MSDN):ui

class Program
    {
        public static int ReadAllBytesFromStream(Stream stream, byte[] buffer)
        {
            int offset = 0;
            int totalCount = 0;
            while (true)
            {
                int bytesRead = stream.Read(buffer, offset, 100);
                if (bytesRead == 0)
                {
                    break;
                }
                offset += bytesRead;
                totalCount += bytesRead;
            }
            return totalCount;
        }

        public static bool CompareData(byte[] buf1, int len1, byte[] buf2, int len2)
        {
            if (len1 != len2)
            {
                Console.WriteLine("Number of bytes in two buffer are diffreent {0}:{1}", len1, len2);
                return false;
            }
            for (int i = 0; i < len1; i++)
            {
                if (buf1[i] != buf2[i])
                {
                    Console.WriteLine("byte {0} is different {1}{2}", i, buf1[i], buf2[i]);
                    return false;
                }
            }
            Console.WriteLine("All byte compare true");
            return true;
        }

        public static void GZipCompressDecompress(string fileName)
        {
            Console.WriteLine("Test compresssion and decompression on file {0}", fileName);
            FileStream infile;
            try
            {
                //Comopress
                infile = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                byte[] buffer = new byte[infile.Length];
                int count = infile.Read(buffer, 0, buffer.Length);
                if (count != buffer.Length)
                {
                    infile.Close();
                    infile.Dispose();
                    Console.WriteLine("Test Failed: Unable to read data from file");
                    return;
                }
                infile.Close();
                MemoryStream ms = new MemoryStream();
                GZipStream compressGZipStream = new GZipStream(ms, CompressionMode.Compress, true);
                Console.WriteLine("Compression");
                compressGZipStream.Write(buffer, 0, buffer.Length);    //從指定字節數組中將壓縮的字節寫入基礎流
                compressGZipStream.Close();
                Console.WriteLine("Original size:{0}, Compressed size:{1}", buffer.Length, ms.ToArray().Length);

                //DeCompress
                ms.Position = 0;
                GZipStream deCompressGZipStream = new GZipStream(ms, CompressionMode.Decompress);
                Console.WriteLine("Decompression");
                byte[] decompressedBuffer = new byte[buffer.Length + 100];

                int totalCount = ReadAllBytesFromStream(deCompressGZipStream, decompressedBuffer);
                Console.WriteLine("Decompressed {0} bytes", totalCount);

                if (!CompareData(buffer, buffer.Length, decompressedBuffer, decompressedBuffer.Length))
                {
                    Console.WriteLine("Error. The two buffers did not compare.");
                }
                deCompressGZipStream.Dispose();
            }
            catch (ArgumentNullException)
            {
                Console.WriteLine("ArgumentNullException:{0}", "Error: The path is null.");
            }
            catch (ArgumentException)
            {
                Console.WriteLine("ArgumentException:{0}", "Error: path is a zero-length string, contains an empty string or one more invlaid characters");
            }
            catch (NotSupportedException)
            {
                Console.WriteLine("NotSupportedException:{0}", "Cite no file, such as 'con:'、'com1'、'lpt1' in NTFS");
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("FileNotFoundException:{0]", "Find no file");
            }
            catch (IOException)
            {
                Console.WriteLine("IOException:{0}", "Occur I/O error");
            }
            catch (System.Security.SecurityException)
            {
                Console.WriteLine("System.Security.SecurityException{0}:", "The calls has no permission");
            }
            catch (UnauthorizedAccessException)
            {
                Console.WriteLine("UnauthorizedAccessException:{0}", "path specified a file that is read-only, the path is a directory, " +
                    "or caller does not have the required permissions");
            }
        }

        static void Main(string[] args)
        {
            GZipCompressDecompress(@"D:\config.ini");
        }
    }
相關文章
相關標籤/搜索