C#调用7z生成自解压文件
1.可执行文件与其他文件处于同一目录中,调用7zr.exe命令行压缩为7z文件
string outputArchive = Path.Combine(outputBasePath, "aaa.7z"); // 输出压缩包路径
string inputDirectory = outputBasePath+"\\"; // 输入文件夹路径
var sevenzaPath = Path.Combine(CurrentRootPath,"Modules", "7za.exe");
string arguments = $"a {outputArchive} {inputDirectory}\\ -m0=LZMA2 -mx=9 -mmt";
ProcessStartInfo processStartInfo = new ProcessStartInfo(sevenzaPath, arguments)
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
using (Process process = Process.Start(processStartInfo))
{
if (process != null)
{
// 等待压缩完成
process.WaitForExit();
// 获取命令行输出
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
Console.WriteLine("压缩完成!");
if (!string.IsNullOrEmpty(output))
{
Console.WriteLine("输出: " + output);
}
if (!string.IsNullOrEmpty(error))
{
Console.WriteLine("错误: " + error);
}
}
}
2.调用7zSD.sfx生成自解压文件
需要编辑好config.txt
string sfxPath = Path.Combine(CurrentRootPath, "Modules", "7zSD.sfx");
string configPath = Path.Combine(CurrentRootPath, "Modules", "config.txt");
string archivePath = Path.Combine(outputBasePath, "aaa.7z");
string outputExePath = Path.Combine(outputBasePath, "aaa.exe");
var command = $"/C copy /b {sfxPath} + {configPath} + {archivePath} {outputExePath}";
// 使用Process启动cmd命令
processStartInfo = new ProcessStartInfo("cmd.exe", command)
{
WorkingDirectory = outputBasePath,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (Process process = Process.Start(processStartInfo))
{
if (process != null)
{
await process.WaitForExitAsync();
Console.WriteLine("7z自解压文件已生成。");
process.Close();
}
}

浙公网安备 33010602011771号