如何在C#应用中获取curl命令的执行结果?
解决C#中调用curl不生成文件并判断执行结果的方案
要实现不生成HTML文件同时获取curl的执行结果,你可以通过以下步骤修改代码:
关键改动说明
- 移除curl的
--output index.html参数,让curl将响应内容输出到标准输出(stdout),而非写入本地文件 - 配置
Process对象以捕获标准输出和错误输出 - 通过curl的退出码(0表示执行成功,非0表示失败)和输出内容判断操作结果
- 等待curl进程执行完成后再进行后续逻辑,避免异步时序问题
修改后的完整代码
using (Process myProcess = new Process()) { int miIntIntervaloActualizacion = GestorConfiguracion.GetIntervaloActualizacion(); string miStrUrl = GestorConfiguracion.GetUrl(); myProcess.StartInfo.UseShellExecute = false; myProcess.StartInfo.FileName = "curl"; // 移除--output参数,添加-s静默模式(可选,减少冗余输出) myProcess.StartInfo.Arguments = $"--url {miStrUrl} -s"; myProcess.StartInfo.CreateNoWindow = false; // 开启标准输出和错误输出的重定向 myProcess.StartInfo.RedirectStandardOutput = true; myProcess.StartInfo.RedirectStandardError = true; myProcess.Start(); // 异步等待进程完成,同时捕获输出和错误信息 string output = await myProcess.StandardOutput.ReadToEndAsync(); string error = await myProcess.StandardError.ReadToEndAsync(); await myProcess.WaitForExitAsync(stoppingToken); // 判断执行结果 if (myProcess.ExitCode == 0) { // 可进一步验证业务层面的"OK"响应 if (output.Trim().Equals("OK", StringComparison.OrdinalIgnoreCase)) { _logger.LogInformation($"IP actualizada en: {DateTime.Now}. 执行成功,响应内容: {output}"); } else { _logger.LogWarning($"IP actualizada en: {DateTime.Now}. curl执行成功但响应内容不符合预期: {output}"); } } else { _logger.LogError($"IP actualizada en: {DateTime.Now}. curl执行失败,退出码: {myProcess.ExitCode},错误信息: {error}"); } await Task.Delay(miIntIntervaloActualizacion, stoppingToken); }
额外说明
-s参数用于让curl进入静默模式,避免输出进度条等冗余信息,不需要的话可以直接移除- 优先通过退出码判断curl是否执行成功,这是最可靠的系统级判断方式;输出内容的"OK"可作为业务层面的二次验证
- 必须等待进程执行完成后再读取输出,否则可能出现读取不完整的情况
- 若你的curl版本支持
--fail参数,可添加该参数,这样当HTTP状态码为4xx/5xx时,curl会返回非0退出码,更便于判断HTTP请求是否成功
内容的提问来源于stack exchange,提问作者Álvaro García
相关产品推荐
相关产品推荐

