我已经在我的机器上安装了7-zip 4.65,路径为C:\Program files。我想在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
}
}
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();
}
或者您可以使用J# zip库(它包含在.Net Framework中) 一个示例:http://weblogs.asp.net/jgalloway/archive/2007/10/25/creating-zip-archives-in-net-without-an-external-library-like-sharpziplib.aspx
如果您希望使用安装在c:\program files中的已安装程序,您可以使用System.Diagnostics.Process
来运行命令行应用程序 - http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx
传递参数也很容易。这里有很多例子 - http://www.c-sharpcorner.com/UploadFile/DipalChoksi/ShellCommandsInCS12032005042031AM/ShellCommandsInCS.aspx