我正在服务器端运行 Web 应用程序控制器应用程序(C#)。当特定的 http 请求到来时,控制器运行外部控制台应用程序,读取数据输入文件并将结果写入输出文件。问题是这个外部控制台应用程序总是输出一个空文件。 如果我通过自己执行外部控制台应用程序(将输入和输出文件作为参数传递)来手动执行此过程,它将按预期创建非空输出结果文件。 这是一个安全问题吗?有解决办法吗?
我启动控制台应用程序的调用如下所示:
string a2tExePath = Path.Combine(Directory.GetCurrentDirectory(), A2T_EXE);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(" ").Append(Path.Combine(uploadFolder, A2T_INPUT)).Append(" ").Append(Path.Combine(uploadFolder, A2T_OUTPUT));
using (System.Diagnostics.Process pProcess = new System.Diagnostics.Process())
{
pProcess.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
pProcess.StartInfo.FileName = a2tExePath;// a2tExePath;
pProcess.StartInfo.Arguments = stringBuilder.ToString(); //argument
pProcess.StartInfo.ErrorDialog = true;
pProcess.StartInfo.UseShellExecute = true;
pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
pProcess.StartInfo.CreateNoWindow = true; //not diplay a windows
pProcess.Start();
//string output = pProcess.StandardOutput.ReadToEnd(); //The output result
log.Info("Executing " + a2tExePath + " " + pProcess.StartInfo.Arguments);
pProcess.WaitForExit();
}
}
我假设您使用的是 Windows。这将在无显示命令提示符下运行任何一个班轮:
public class Cmd
{
public CommandLineResult Run(string singleLine)
{
var startInfo = new ProcessStartInfo("cmd.exe")
{
Arguments = $"/c \"{singleLine}\"",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
var process = Process.Start(startInfo);
var stdErr = string.Empty;
process!.ErrorDataReceived += new DataReceivedEventHandler((sender, e) => { stdErr += e.Data });
process.BeginErrorReadLine();
var stdOut = process?.StandardOutput.ReadToEnd();
process?.WaitForExit();
return new CommandLineResult
{
ExitCode = process?.ExitCode ?? -1,
StandardOut = stdOut!,
StandardErr = stdErr!,
};
}
}
public class CommandLineResult
{
public int ExitCode { get; init; }
public string StandardOut { get; init; } = null!;
public string StandardErr { get; init; } = null!;
public bool IsSuccess => ExitCode == 0;
public string StandardAll = string.Join(Environment.NewLine, new[] { StandardOut, StandardErr });
}
您可以这样使用:
var inputPath = Path.Combine(uploadFolder, A2T_INPUT);
var outputPath = Path.Combine(uploadFolder, A2T_OUTPUT);
var singleLine = $"{a2tExePath} {inputPath} {outputPath}";
var result = new Cmd().Run(singleLine);