Sample C# .net code for zipping a file using 7zip

2020-03-22 08:24发布

问题:

I have installed 7-zip 4.65 on my machine at C:\Program files. I want to use it in C# code to zip a file. The file name will be provided by the user dynamically. Can any one please provide a sample code on how to use 7zip in C# code?

回答1:

lots of answer given above but i used this below mention code to zip or unzip a file using 7zip

you must have 7zip application in your system .

     public void ExtractFile(string source, string destination)
        {
            // If the directory doesn't exist, create it.
            if (!Directory.Exists(destination))
                Directory.CreateDirectory(destination);

            string zPath = @"C:\Program Files\7-Zip\7zG.exe";
// change the path and give yours 
            try
            {
                ProcessStartInfo pro = new ProcessStartInfo();
                pro.WindowStyle = ProcessWindowStyle.Hidden;
                pro.FileName = zPath;
                pro.Arguments = "x \"" + source + "\" -o" + destination;
                Process x = Process.Start(pro);
                x.WaitForExit();
            }
            catch (System.Exception Ex) {
              //DO logic here 
              }
        }

to create zip file

public void CreateZip()
{
    string sourceName = @"d:\a\example.txt";
    string targetName = @"d:\a\123.zip";
    ProcessStartInfo p = new ProcessStartInfo();
    p.FileName = @"C:\Program Files\7-Zip\7zG.exe";
    p.Arguments = "a -tgzip \"" + targetName + "\" \"" + sourceName + "\" -mx=9";
    p.WindowStyle = ProcessWindowStyle.Hidden;
    Process x = Process.Start(p);
    x.WaitForExit();
}


回答2:

Instead of the binary version you need the source code.

This can be get as the LZMA SDK.

There you'll find a folder CS that contains a C# implementation of the algorithm for 7zip files.



回答3:

Have you tried this C# interface for 7zip: http://www.codeproject.com/KB/DLL/cs_interface_7zip.aspx

[edit] Looks like this has been answered already: Free compression library for C# which supports 7zip (LZMA)

further libraries:

http://www.eggheadcafe.com/tutorials/aspnet/064b41e4-60bc-4d35-9136-368603bcc27a/7zip-lzma-inmemory-com.aspx

http://sevenzipsharp.codeplex.com/

http://www.7-zip.org/sdk.html - From the official site so probably best to use this



回答4:

Or you can use the J# zip library (which is included in the .Net Framework) a sample: http://weblogs.asp.net/jgalloway/archive/2007/10/25/creating-zip-archives-in-net-without-an-external-library-like-sharpziplib.aspx



回答5:

I suppose if you wish to use the installed one you have in c:\program files, you could just use System.Diagnostics.Process to run command line apps - http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx

Passing parameters is easy too. There are plenty of examples here - http://www.c-sharpcorner.com/UploadFile/DipalChoksi/ShellCommandsInCS12032005042031AM/ShellCommandsInCS.aspx



标签: c# 7zip