using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

using SevenZip;

class Progress : ICodeProgress
{
    public void SetProgress(Int64 inSize, Int64 outSize)
    {
        Console.WriteLine("读入{0}KB,处理后大小:{1}字节", inSize/1024, outSize);
    }
}

class Program
{
    static void Main(string[] args)
    {
        /* 压缩 */
        CoderPropID[] propIDs = 
				{
					CoderPropID.DictionarySize,
					CoderPropID.PosStateBits,
					CoderPropID.LitContextBits,
					CoderPropID.LitPosBits,
					CoderPropID.Algorithm,
					CoderPropID.NumFastBytes,
					CoderPropID.MatchFinder,
					CoderPropID.EndMarker
				};

        object[] encode_properties = 
				{
					1<<23,
					2,
					3,
					0,
					2,
					128,
					"bt4",
					false
				};

        SevenZip.Compression.LZMA.Encoder encoder = 
            new SevenZip.Compression.LZMA.Encoder();
        encoder.SetCoderProperties(propIDs, encode_properties);

        FileStream inStream = new FileStream(@"D:\MyDoc\Desktop\test.txt", 
            FileMode.Open, FileAccess.Read);
        FileStream outStream = new FileStream(@"D:\MyDoc\Desktop\test.txt.7z", 
            FileMode.Create, FileAccess.Write);
        encoder.WriteCoderProperties(outStream);

        for (int i = 0; i < 8; i++)
        {
            outStream.WriteByte((Byte)(inStream.Length >> (8 * i)));
        }

        //压缩进度
        //Progress p = new Progress();
        encoder.Code(inStream, outStream, -1, -1, /*p*/null);
        inStream.Close();
        outStream.Close();


        /* 解压 
        inStream = new FileStream(@"D:\MyDoc\Desktop\test.txt.7z", 
            FileMode.Open, FileAccess.Read);
        outStream = new FileStream(@"D:\MyDoc\Desktop\test.decode.txt", 
            FileMode.Create, FileAccess.Write);
        
        byte[] decode_properties = new byte[5];
        int n = inStream.Read(decode_properties, 0, 5);
        if (n != 5)
        {
            Console.WriteLine("read encode_properties error.");
            return;
        }

        SevenZip.Compression.LZMA.Decoder decoder = 
        new SevenZip.Compression.LZMA.Decoder();
        decoder.SetDecoderProperties(decode_properties);

        long outSize = 0;
        for (int i = 0; i < 8; i++)
        {
            int v = inStream.ReadByte();
            if (v < 0)
            {
                Console.WriteLine("read outSize error.");
                return;
            }
            outSize |= ((long)(byte)v) << (8 * i);
        }
        long compressedSize = inStream.Length - inStream.Position;
        decoder.Code(inStream, outStream, compressedSize, outSize, null);

        inStream.Close();
        outStream.Close();
        */
    }
}

 点此下载源码

 


本文链接地址: 在C#中使用lzma SDK压缩与解压缩文件
http://qingfengju.com/index.asp?id=319

分类:Win32/C++ 查看次数:7810 发布时间:2012-12-4 20:50:57