惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

AI
AI
Engineering at Meta
Engineering at Meta
T
The Blog of Author Tim Ferriss
Latest news
Latest news
Microsoft Azure Blog
Microsoft Azure Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Simon Willison's Weblog
Simon Willison's Weblog
M
MIT News - Artificial intelligence
V
Visual Studio Blog
N
Netflix TechBlog - Medium
P
Palo Alto Networks Blog
C
Cybersecurity and Infrastructure Security Agency CISA
阮一峰的网络日志
阮一峰的网络日志
P
Proofpoint News Feed
G
Google Developers Blog
MongoDB | Blog
MongoDB | Blog
V
Vulnerabilities – Threatpost
AWS News Blog
AWS News Blog
美团技术团队
博客园 - 聂微东
The GitHub Blog
The GitHub Blog
Stack Overflow Blog
Stack Overflow Blog
The Hacker News
The Hacker News
C
CXSECURITY Database RSS Feed - CXSecurity.com
L
Lohrmann on Cybersecurity
B
Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
爱范儿
爱范儿
Hacker News - Newest:
Hacker News - Newest: "LLM"
Hugging Face - Blog
Hugging Face - Blog
O
OpenAI News
W
WeLiveSecurity
Cisco Talos Blog
Cisco Talos Blog
Google Online Security Blog
Google Online Security Blog
T
Tenable Blog
Attack and Defense Labs
Attack and Defense Labs
C
Cisco Blogs
G
GRAHAM CLULEY
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Y
Y Combinator Blog
Microsoft Security Blog
Microsoft Security Blog
Help Net Security
Help Net Security
The Last Watchdog
The Last Watchdog
S
Security @ Cisco Blogs
C
CERT Recently Published Vulnerability Notes
博客园 - 【当耐特】
T
Troy Hunt's Blog
Cloudbric
Cloudbric
IT之家
IT之家

博客园 - 无名365

.NET 2.0 JSON Parser Provisioning 是什么意思? SOA与云计算 Good understand on WCF Data Contract & Serialization WCF DataContract EmitDefaultValue a xml configuration for unity and interception CodeRun Studio - A free cloud develop and debug service for .Net Cloud IDE 10个最“优秀”的代码注释 Compress and Decompress JQuery Mobile 1.0 Released, Gets Mixed Reaction Interceptor in Unity and Policy Injection in Unity Configuring Unity Container with Policy Injection Configuration Unity Configuration Node Unity Configuration from Separate Configuration File IoC and Unity - Configuration Objects and the Art of Data Modeling AppFabric Cache - Cache Cluster EF - How to delete an object without retrieving it LINQ to SQL Extension: Batch Deletion with Lambda Expression
Programmatically Compress and Decompress Files using c#
无名365 · 2011-11-25 · via 博客园 - 无名365

2011-11-25 13:36  无名365  阅读(392)  评论()    收藏  举报

This lesson is very easy. This lesson focuses on how to compress and decompress files programmatically using .NET Framework and C# -or any language that supports .NET of course.-

Currently .NET Framework supports two types of compression algorithms:

  • Deflate
    This is a very simple algorithm, used for simple compression and decompression operations. Don't use this algorithm except if you intend to use compressed data only in your application because this algorithm is not compatible with any compression tool.
  • GZIP
    This algorithm uses internally the Deflate algorithm. This algorithm includes a cyclic redundancy check value for detecting data corruption. Also it’s compatible with most compression tools because it writes headers to the compressed file, so compression tools -like WinZip and WinRAR- can easily access the compressed file and decompress it as well. This algorithm also can be extended to use other algorithms internally other than Deflate.

For a complete GZIP reference, see RFC 1952 (GZIP File Format Specification).

The most powerful compression tool now is WinRAR.

Fortunately, whether using Deflate or GZIP in .NET, code is the same; the only thing that needs to change is the class name.

Deflate and GZIP can be found in the namespace System.IO.Compression that resides on assembly System.dll. This namespace contains only three types, the two algorithm implementation classes DeflateStream and GZipStream -both inherit directly from System.IO.Stream class-, and an enumeration CompressionMode that defines the operation (compression or decompression).

Compressing a File

The code for compression is very simple:

Code snippets in this lesson rely on the fact that you added two using (Imports in VB) statements, System.IO and System.IO.Compression.

Collapse | Copy Code

string fileToBeCompressed =
    "D:My Great Word Document.doc";
string zipFilename =
    "D:CompressedGreatDocument.zip";

using (FileStream target =
    new FileStream(zipFilename,
        FileMode.Create, FileAccess.Write))
using (GZipStream alg =
    new GZipStream(target, CompressionMode.Compress))
{
    byte[] data = File.ReadAllBytes(fileToBeCompressed);
    alg.Write(data, 0, data.Length);
    alg.Flush();
}

Code Explanation

If you are going to compress a file, then you must specify the CompressionMode.Compress option, and also you must specify a Stream that the data will be written to.
After creating the class, you can compress the data by using its Write() method.

If you intended to use the Deflate algorithm, just change the class name to DeflateStream.

Decompressing a File

The code that decompresses a compressed file is very similar:

Collapse | Copy Code

string compressedFile =
    "D:CompressedGreatDocument.zip";
string originalFileName =
    "D:My Great Word Document.doc";

using (FileStream zipFile =
    new FileStream(compressedFile,
        FileMode.Open, FileAccess.Read))
using (FileStream originalFile =
    new FileStream(originalFileName,
        FileMode.Create, FileAccess.Write))
using (GZipStream alg =
    new GZipStream(zipFile, CompressionMode.Decompress))
{
    while (true)
    {
                byte[] buffer = new byte[100];
                int bytesRead = alg.Read(buffer, 0, buffer.Length);

        originalFile.Write(buffer, 0, returnedBytes);

        if (bytesRead != buffer.Length)
            break;
    }
}

Code Explanation

First, we create a file stream to read the ZIP file, and then we created our algorithm class that encapsulates the file stream for decompressing it.
Then we created a file stream for the original file, for writing the decompressed data.
After that, we read the data compressed 100bytes after each other -you may prefer more- and write this data to the original file stream.

By encapsulating disposable objects into using statements, you become assured that every object will be disposed in a certain point -end of the using statement- and no object will retain in memory.

From http://www.codeproject.com/Articles/66269/Programmatically-Compress-and-Decompress-Files.aspx