gpt4 book ai didi

c# - 命令行输入和 UseShellExecute == true

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

我有一个程序,基本上剩下的就是通过 CMD.exe 调用命令。

我需要在我当前的工作目录中打开 CMD.exe(我知道我可以做 Porcess.Start(CMD.exe))

然后我需要让程序在 cmd.exe 中键入一个特定的字符串。留在我当前的工作目录中。我不能使用“UseShellExecute == false”,因为它会杀死 shell,我需要 shell 才能工作。

显然我需要更具体一些。所以,我试图写入 cmd.exe 的文本是 "clingo.exe\"Constants.txt\"\"Solver.txt\"\"Nodes.txt\">\"Solved.txt\""。 clingo.exe 是一个答案集编译器,我在文件 Constants、Solver 和 Nodes 上使用它来获得通过管道传输到 Solved 的解决方案。所有这些文件都在一个目录中。

最佳答案

首先,我想知道为什么您认为 UseShellExecute=false 不适合您。有没有可能你只是没有正确使用它?

这是您的最佳选择。这适用于 99% 的应用:

ProcessStartInfo psi = new ProcessStartInfo
{
FileName = "clingo.exe",
Arguments = "\"Constants.txt\" \"Solver.txt\" \"Nodes.txt\"",
RedirectStandardOutput = true,
UseShellExecute = false
};

using(Process p = Process.Start(psi))
using(Stream s = File.Create("Solved.txt"))
{
p.StandardOutput.CopyTo(s);
p.WaitForExit();
}

这是一个罕见的应用程序选项,它不喜欢以标准方式传递的参数,但可以与 cmd.exe 一起使用:

ProcessStartInfo psi = new ProcessStartInfo
{
FileName = "cmd.exe",
RedirectStandardInput = true,
UseShellExecute = false // note this applies to cmd.exe specifically,
// NOT the processes that you start from cmd.exe
};

using(Process p = Process.Start(psi))
{
p.StandardInput.WriteLine("clingo \"Constants.txt\" \"Solver.txt\" \"Nodes.txt\" > \"Solved.txt\"");
p.StandardInput.WriteLine("exit");
p.WaitForExit();
}

您可能还需要重定向 StandardOutput 和 StandardError 才能正常工作——我忘记了!

关于c# - 命令行输入和 UseShellExecute == true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13639454/

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