gpt4 book ai didi

c# - 在 C# 中运行/生成命令与文件

转载 作者:太空宇宙 更新时间:2023-11-03 20:16:42 25 4
gpt4 key购买 nike

我可以在 C# 中执行以下操作:

var pSpawn = new Process
{
StartInfo = { WorkingDirectory = @"C:\temp", FileName = fileToRun, CreateNoWindow = true }
};
pSpawn.Start();

这工作正常....但是我想知道是否有一种方法可以运行命令(即:“dir/b”)而不必将其封装在批处理文件中?

最佳答案

只需启动 cmd.exe 并传递所需的参数

 var pSpawn = new Process
{
StartInfo =
{
WorkingDirectory = @"C:\temp",
FileName = "cmd.exe",
Arguments ="/K dir /b" }
};

pSpawn.Start();

我添加了参数 /K 使命令窗口保持打开状态,因此可以看到命令 dir 的输出。
当然,我认为您真的很想了解命令的输出。
在这种情况下,您可以使用这样的方法:

StringBuilder sb = new StringBuilder();
var pSpawn = new Process
{
StartInfo =
{
WorkingDirectory = @"C:\temp",
FileName = "cmd.exe",
Arguments ="/c dir /b",
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false
}
};

pSpawn.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data);
pSpawn.Start();
pSpawn.BeginOutputReadLine();
pSpawn.WaitForExit();
Console.WriteLine(sb.ToString());

关于c# - 在 C# 中运行/生成命令与文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16214226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com