logo search
CSharp_Prog_Guide

Компиляция кода

Чтобы запустить этот пример, необходимо предоставить подходящую учетную запись пользователя или группы. В этом примере используется объект File; однако та же самая процедура используется для классов FileInfo, Directory и DirectoryInfo.

How to: Compress Files

Use the GZipStream class to compress and decompress data. The following code example creates a file (test.txt) in the current directory, fills it with text, and displays the contents of the file to the console. The code then uses the GZipStream class to create a compressed version of the file (test.txt.gz) and compares the size of the two files. Finally, the code reads in the compressed file, decompresses it, and writes out a new file (test.txt.gz.txt) to the current directory. The code then displays the contents of the decompressed file.

You can also use the DeflateStream class to compress and decompress data.

Example

using System;

using System.Collections.Generic;

using System.IO;

using System.IO.Compression;

public class CompressionSnippet

{

public static void Main()

{

string path = "test.txt";

// Create the text file if it doesn't already exist.

if (!File.Exists(path))

{

Console.WriteLine("Creating a new test.txt file");

string[] text = new string[] {"This is a test text file.",

"This file will be compressed and written to the disk.",

"Once the file is written, it can be decompressed",

"using various compression tools.",

"The GZipStream and DeflateStream class use the same",

"compression algorithms, the primary difference is that",

"the GZipStream class includes a cyclic redundancy check",

"that can be useful for detecting data corruption.",

"One other side note: both the GZipStream and DeflateStream",

"classes operate on streams as opposed to file-based",

"compression; data is read on a byte-by-byte basis, so it",

"is not possible to perform multiple passes to determine the",

"best compression method. Already compressed data can actually",

"increase in size if compressed with these classes."};

File.WriteAllLines(path, text);

}