C#中逐个调用第三方程序处理解压文件时仅执行一次的问题求助
问题分析与修复
你的代码在调用wxPirs.exe时仅处理第一个文件就停止,核心有两个关键错误:
- 参数传递错误:你把整个文件列表直接传给
Process.Start的参数,而wxPirs.exe需要的是单个文件路径作为输入,这会导致程序参数解析异常,无法继续处理后续文件。 - 重复读取目录:循环中每次都调用
GetAllFiles(unpackedPath),既浪费性能,还可能因wxPirs处理文件时修改目录内容,导致列表出现不可预期的变化。
修正后的代码
static void unpackRar() { string homePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); string packedPath = Path.Combine(homePath, "XBLA"); string unpackedPath = Path.Combine(homePath, "XBLA_Unpacked"); string unrarPath = Path.Combine(homePath, "unRAR.exe"); using (var process = Process.Start(unrarPath, $"x \"{packedPath}\\*.rar\" \"{unpackedPath}\"")) { process.WaitForExit(); } } static List<string> GetAllFiles(string unpackedPath) { return Directory.GetFiles(unpackedPath, "*", SearchOption.AllDirectories).ToList(); } static void unPirs() { string homePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); string unpackedPath = Path.Combine(homePath, "XBLA_Unpacked"); string wxPirsPath = Path.Combine(homePath, "wxPirs.exe"); // 提前缓存文件列表,避免重复读取目录 var fileList = GetAllFiles(unpackedPath); foreach (var filePath in fileList) { Console.WriteLine(filePath); // 传递单个文件路径,用引号包裹避免路径含空格导致解析失败 using (var process = Process.Start(wxPirsPath, $"\"{filePath}\"")) { process.WaitForExit(); } } }
额外优化说明
- 用
Path.Combine拼接路径:避免手动拼接字符串时的斜杠错误,兼容不同系统路径格式。 - 用
using包裹Process对象:确保进程资源被正确释放,避免资源泄漏。 - 路径添加双引号:解决文件/目录路径含空格时,第三方程序无法正确解析参数的问题。
内容的提问来源于stack exchange,提问作者cmclark00
相关产品推荐
相关产品推荐

