c# gzip解压缩

//引用
            using System.IO.Compression;
            //解压缩类
            GZipStream
            //解压缩实例
            ......
            HttpWebResponse httpRequest = (HttpWebResponse)httpLogin.GetResponse();
            Stream HttpResStream= httpRequest.GetResponseStream();
            GZipStream gzip = new GZipStream(HttpResStream, CompressionMode.Decompress) ;
            //对解压缩后的字符串信息解析
           while ((len = gzip.Read(bytes, 0, bytes.Length)) > 0)
            {
               line =  System.Text.Encoding.Default.GetString(bytes);
            }

http://msdn.microsoft.com/zh-cn/library/system.io.compression.gzipstream(v=vs.80).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

using System;
using System.IO;
using System.IO.Compression;

public class GZipTest
{
    public static int ReadAllBytesFromStream(Stream stream, byte[] buffer) 
    {
    // Use this method is used to read all bytes from a stream.
    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) 
    {
        // Use this method to compare data from two different buffers.
        if (len1 != len2) 
        { 
        Console.WriteLine("Number of bytes in two buffer are different {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 bytes compare.");
    return true; 
    }

public static void GZipCompressDecompress(string filename)
    {
    Console.WriteLine("Test compression and decompression on file {0}", filename);
    FileStream infile;
        try
        {
        // Open the file as a FileStream object.
        infile = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
        byte[] buffer = new byte[infile.Length];
        // Read the file to ensure it is readable.
        int count = infile.Read(buffer, 0, buffer.Length);
            if ( count != buffer.Length) 
            {
            infile.Close();
            Console.WriteLine("Test Failed: Unable to read data from file"); 
            return;
            }
        infile.Close();
        MemoryStream ms = new MemoryStream();
        // Use the newly created memory stream for the compressed data.
        GZipStream compressedzipStream = new GZipStream(ms , CompressionMode.Compress, true);
        Console.WriteLine("Compression");
        compressedzipStream.Write(buffer, 0, buffer.Length);
        // Close the stream.
        compressedzipStream.Close();
        Console.WriteLine("Original size: {0}, Compressed size: {1}", buffer.Length, ms.Length);

// Reset the memory stream position to begin decompression.
        ms.Position = 0;
        GZipStream zipStream = new GZipStream(ms, CompressionMode.Decompress);
        Console.WriteLine("Decompression");
        byte[] decompressedBuffer = new byte[buffer.Length + 100];
        // Use the ReadAllBytesFromStream to read the stream.
        int totalCount = GZipTest.ReadAllBytesFromStream(zipStream, decompressedBuffer);
        Console.WriteLine("Decompressed {0} bytes", totalCount);

if( !GZipTest.CompareData(buffer, buffer.Length, decompressedBuffer, totalCount) ) 
        {
        Console.WriteLine("Error. The two buffers did not compare.");
        }
    zipStream.Close(); 
        } // end try
        catch (InvalidDataException)
        {
            Console.WriteLine("Error: The file being read contains invalid data.");
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Error:The file specified was not found.");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("Error: path is a zero-length string, contains only white space, or contains one or more invalid characters");
        }
        catch (PathTooLongException)
        {
            Console.WriteLine("Error: The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.");
        }
        catch (DirectoryNotFoundException)
        {
            Console.WriteLine("Error: The specified path is invalid, such as being on an unmapped drive.");
        }
        catch (IOException)
        {
            Console.WriteLine("Error: An I/O error occurred while opening the file.");
        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine("Error: path specified a file that is read-only, the path is a directory, or caller does not have the required permissions.");
        }
        catch (IndexOutOfRangeException)
        {
            Console.WriteLine("Error: You must provide parameters for MyGZIP.");
        }
    }
    public static void Main(string[] args)
    {
        string usageText = "Usage: MYGZIP <inputfilename>";
        //If no file name is specified, write usage text.
        if (args.Length == 0)
        {
            Console.WriteLine(usageText);
        }
        else
        {
            if (File.Exists(args[0]))
                GZipCompressDecompress(args[0]);
        }
    }
}

时间: 2024-08-10 06:48:08

c# gzip解压缩的相关文章

c语言使用zlib实现文本字符的gzip压缩与gzip解压缩

网络上找到的好多方法在解压缩字符串的时候会丢失字符,这里是解决方法: http://stackoverflow.com/questions/21186535/compressing-decompressing-char-array-using-zlib-some-characters-missing 基于此,笔者修改了一下,由于是初学者,只按照编译器不报错的原则修改了一下,能运行 打开vc++6.0新建控制台程序程序,配置好zdll.lib,把zlib1.dll放置到合适的位置主程序main.c

java GZIP压缩与解压缩

1.GZIP压缩 public static byte[] compress(String str, String encoding) { if (str == null || str.length() == 0) { return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip; try { gzip = new GZIPOutputStream(out); gzip.

Linux基础篇-压缩、解压缩命令

压缩格式:gz,bz2,xz,zip,Z compress:FILENAME.Z  早期的压缩命令 uncompress gzip:  .gz   只能压缩文件 gzip /PATH/TO/SOMEFILE :压缩完成后会删除源文件 -d:解压缩 -#:1-9 指定压缩比 默认是6: gunzip; gunzip /PATH/TO/SOMEFILE.gz:解压完成后会删除原文件 zcat /PATH/TO/SOMEFILE.gz:不解压的情况下,查看文本文件的内容: bzip2: .bz2 只能

Linux学习笔记&lt;十三&gt;——文件压缩、解压缩和归档

压缩.解压缩命令: 1.compress/uncompress:压缩格式为Z,文件后缀为.Z compress /path/to/file uncompress /path/to/file.Z 2.gzip/gunzip/zcat:压缩格式为gz,文件后缀为.gz gzip [OPTION] /path/to/file:,压缩文件保存在被压缩文件的目录,压缩完成后会删除原文件 -v|verbose:显示指令执行过程 -d:解压缩,解压缩完成后删除原压缩文件 -#:1-9,指定压缩比,默认为6,数

Linux CentOS 7 中打包压缩工具gzip、bzip2、xz、zip、tar

一. 压缩打包介绍 常见压缩文件 windows .rar  .zip  .7z linux: .rar .zip .gz .bz2 .xz .tar.gz .tar.bz2  .tar.xz 二. gzip压缩工具 gzip压缩文件: gzip 只能压缩文件不能压缩目录.**gzip 1.txt 压缩完成原文件删除**生成1.txt文件: find /etc/ -type f -name  "*.conf" -exec cat {} >> /tmp/fxq/1.txt \

2016-8-28 压缩解压缩及归档 while脚本

文件管理命令――压缩解压缩及归档基本工具 压缩.解压缩命令 压缩格式:gz, bz2, xz, zip, Z 压缩算法:算法不同,压缩比也会不同: 早期    压缩:        compress(压缩比很小): FILENAME.Z ―― 压缩后的文件名    解压:        uncompress gzip.bzip2.xz只能压缩文件,并且默认压缩完成后删除源文件,zip可以压缩目录 gzip: .gz    gzip /PATH/TO/SOMEFILE:压缩完成后会删除原文件   

【linux_笔记】Linux_文件管理命令—压缩解压缩及归档基本工具

学习资源来自:www.magedu.com 学习记录过程中难免出现错误,如有发现,还望大神们指出. 示例操作部分有的与历史操作有关,如果先前的示例操作没有执行过的话,可能会有部分示例的操作无法执行.示例仅供参考.(示例见附件) 文件管理命令--压缩解压缩及归档基本工具 压缩.解压缩命令 压缩格式:gz, bz2, xz, zip, Z 压缩算法:算法不同,压缩比也会不同: 早期    压缩:        compress(压缩比很小): FILENAME.Z -- 压缩后的文件名    解压:

J2EE和android的GZIP测试

使用GZIP进行数据压缩传输实验,服务端是J2EE,使用HTTP的POST方式进行数据请求. 为了方便测试,刚开始在J2EE的环境下写了一个TestCase去调用J2EE写的服务,忘记写GZIP解压代码,数据居然能够正常解压. 好!因为服务是最终提供给android端来调用的,所以改换成android客户端来测试. 刚开始没有显式调用GZIP解压,发现数据死活显示不正确,截获到的数据如下: ??V*J-v?O?T?RR?q??SR?? ?l??t???募[email protected]??2

客户端HttpClient处理 Servlet Gzip

服务端采用gzip对文本内容进行压缩处理,客户端使用HttpClient获取数据并进行gzip解压缩. 一: 服务端 public class GzipTestServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setH