First steps. Create a new C# project in Visual Studio. Here we will show a console application. Next, you need to download the executable.
Detail Right-click on your project name in the Solution Explorer and select Add Existing Item.
Detail You must specify "Copy if newer" or "Copy always" to copy files such as executables to the output directory.
Implementation. The source file name is the name of the text file you added to the project. The target name is the location of the archive you want to create.
Note If the archive is already there, you will have to delete it or tell 7-Zip to overwrite it.
Detail We set the FileName to the name of the 7za.exe executable in the project. Pay close attention to the quotes in Arguments.
Info In this example, I use GZip compression. We actually start the Process and execute it.
Warning The Windows OS can cause problems here if you are not an administrator on your PC.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
class Program
{
static void Main()
{
string sourceName = "ExampleText.txt";
string targetName = "Example.gz";
// Initialize process information.
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = "7za.exe";
// Use 7-zip.
// Specify a=archive and -tgzip=gzip
// and then target file in quotes followed by source file in quotes.
p.Arguments = "a -tgzip \"" + targetName + "\" \"" +
sourceName + "\" -mx=9";
p.WindowStyle = ProcessWindowStyle.Hidden;
// Start process and wait for it to exit.Process x = Process.Start(p);
x.WaitForExit();
}
}
Verify results. Open the bin\Debug or bin\Release folder in your project's directory, and you should see the compressed file. Extract that file with 7-Zip, and it will have the same data.
Tip First make sure all the files are being copied and the Arguments syntax is correct. The quotes in the syntax are important.
Compression level. You want the smallest possible compressed files, but don't want to wait for hours. On the example, I use -mx=9, which sets the maximum for Zip and GZip.
Archive type. You may need something different from GZip in your program. The ".7z" format probably has the best compression ratio.
Info If you want to use HTTP compression, use GZip, but if you are archiving, then I suggest 7z.
A summary. We invoked the 7-Zip executable from C# code. Sometimes it is best to use an open-source exe like 7-Zip. This will help compression ratios.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 14, 2022 (edit).