我已经在计算机上的C:\ Program文件中安装了7-zip 4.65。我想在C#代码中使用它来压缩文件。文件名将由用户动态提供。谁能在C#代码中提供有关如何使用7zip的示例代码?
上面给出了很多答案,但是我使用下面提到的代码使用7zip压缩或解压缩文件
您的系统中必须有7zip应用程序。
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
}
}
Run Code Online (Sandbox Code Playgroud)
创建压缩文件
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();
}
Run Code Online (Sandbox Code Playgroud)
您是否尝试过 7zip 的 C# 接口:http://www.codeproject.com/KB/DLL/cs_interface_7zip.aspx
[编辑] 看起来这个问题已经得到了回答:Free Compression Library for C# that support 7zip (LZMA)
更多库:
http://sevenzipsharp.codeplex.com/
http://www.7-zip.org/sdk.html - 来自官方网站,所以可能最好使用这个