How to extract 7z file to a folder C# .net

This article will show you how to extract .7z, .zip, .rar file using 7z.exe in C#.net.

Here we add the code to control the 7-Zip executable. In the first part of the code, we specify the source file name and the target file name. The source file name is the name of the file that you want to extract. The target name is the location where this file is to be extracted.

We use ProcessStartInfo and set the Filename to the name of the 7zG.exe executable in the project. Pay close attention to how the quotes are escaped and used in the line where Arguments is set. In this example, I use 7Zip compression.

Here is code

public void ExtractFile(string source, string destination)
{
    string zPath = @"C:\Program Files\7-Zip\7zG.exe";
    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) { }
}

On the same way, How to create .zip file using 7z file, you just have to change the commandline as below

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();
}

You can find help file on 7z at location “C:\Program Files\7-Zip\ 7-zip.chm”

Advertisements
This entry was posted in C#.NET, MVC and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s