我在我的机器上的 C:\Program 文件中安装了 7-zip 4.65。我想在 C# 代码中使用它来压缩文件。文件名将由用户动态提供。任何人都可以提供有关如何在 C# 代码中使用 7zip 的示例代码吗?
5 回答
上面给出了很多答案,但我使用下面提到的代码来使用 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
}
}
创建 zip 文件
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();
}
您是否尝试过 7zip 的 C# 接口:http: //www.codeproject.com/KB/DLL/cs_interface_7zip.aspx
[编辑] 看起来已经回答了这个问题:支持 7zip (LZMA) 的 C# 的免费压缩库
更多图书馆:
http://sevenzipsharp.codeplex.com/
http://www.7-zip.org/sdk.html - 来自官方网站,所以最好使用这个
我想如果你想使用你在 c:\program 文件中安装的,你可以用它System.Diagnostics.Process
来运行命令行应用程序 -
http://msdn.microsoft.com/en-us/library/system.diagnostics.process .aspx
传递参数也很容易。这里有很多例子 - http://www.c-sharpcorner.com/UploadFile/DipalChoksi/ShellCommandsInCS12032005042031AM/ShellCommandsInCS.aspx
或者您可以使用 J# zip 库(包含在 .Net 框架中)作为示例:http ://weblogs.asp.net/jgalloway/archive/2007/10/25/creating-zip-archives-in-net -没有外部库-like-sharpziplib.aspx