这位兄弟贴了段代码,目的是用Process类执行控制台命令并获执行该命令的输出信息,但执行失败了,代码这样的
var psiNpm = new ProcessStartInfo
{
FileName = "cmd.exe",
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false
};
var pNpmRun = Process.Start(psiNpm);
pNpmRun.StandardInput.WriteLine("/c echo \"Fuck World\"");
pNpmRun.StandardInput.WriteLine("echo \"Fuck World\"");
var output = pNpmRun.StandardOutput.ReadToEnd();
pNpmRun.StandardInput.WriteLine("exit");
pNpmRun.WaitForExit();
Console.WriteLine(output);
然后ChatGPT帮他解决了
Process process = new Process();
//process.StartInfo.FileName = "cmd.exe";
process.StartInfo.FileName = "cmd";
//process.StartInfo.Arguments = "/c echo \"Fuck World\"";
process.StartInfo.Arguments = "/c echo Fuck World";
//process.StartInfo.Arguments = "/c dotnet --list-sdks";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
process.WaitForExit();
string output = process.StandardOutput.ReadToEnd();
Console.WriteLine(output);
热心网友贴了段代码说是自己执行失败了,但贴主和我都能执行成功。
我对图中代码做了点修改,如下:
var startInfo = new ProcessStartInfo()
{
FileName = "cmd",
Arguments = "/c echo Hello World",
UseShellExecute = false,
RedirectStandardOutput = true
};
startInfo.Arguments = "/c dotnet --list-sdks";
//if (!string.IsNullOrEmpty(dir))
// startInfo.WorkingDirectory = dir;
var p = new Process
{
StartInfo = startInfo,
EnableRaisingEvents = true
};
var outputBuilder = new StringBuilder();
p.OutputDataReceived += (sender, args) => outputBuilder.Append(args.Data+"\r\n");
p.Start();
p.BeginOutputReadLine();
p.WaitForExit();
p.CancelOutputRead();
Console.WriteLine(outputBuilder.ToString());
其实贴主第一次放出来的代码调整下顺序也是能执行成功的,像这样:
var psiNpm = new ProcessStartInfo
{
FileName = "cmd",
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false
};
var pNpmRun = Process.Start(psiNpm);
pNpmRun.StandardInput.WriteLine("echo \"Hello World\"");
pNpmRun.StandardInput.WriteLine("exit");
pNpmRun.WaitForExit();
var output = pNpmRun.StandardOutput.ReadToEnd();
Console.WriteLine(output);
等待执行结束pNpmRun.WaitForExit();
再去读取输出信息var output = pNpmRun.StandardOutput.ReadToEnd();
最后贴主给出了final solution
我复制粘贴执行了下,没问题~
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Execute().Wait();
}
static async Task Execute()
{
var psi = new ProcessStartInfo()
{
FileName = "dotnet",
Arguments = "--list-sdks"
};
using var proc=Process.Start(psi)!;
await proc.WaitForExitAsync();
}
以上是C#四种不同的方式使用Porcess执行命令后获取该命令的输出信息。
代码复制粘贴就能执行~