gpt4 book ai didi

C#隐藏cmd窗口需要输入

转载 作者:太空宇宙 更新时间:2023-11-03 15:13:49 26 4
gpt4 key购买 nike

在我的代码中,我需要运行很多 cmd 命令。所有这些都必须隐藏起来。作为示例,我将向您展示 2 个命令的代码。

string cmdText = @"/c regsvr32 vbscript.dll";
System.Diagnostics.Process temp = new System.Diagnostics.Process();
temp.StartInfo.Arguments = cmdText;
temp.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
temp.StartInfo.FileName = "cmd.exe";
temp.EnableRaisingEvents = true;
temp.Start();
temp.WaitForExit();
cmdText = @"/c regsvr32 jscript.dll";
temp.StartInfo.Arguments = cmdText;
temp.Start();
temp.WaitForExit();

现在的问题是某些命令(例如 gpupdate/force)需要输入(例如“Y/N”)。如何将此输入提供给 cmd?

最佳答案

您需要读取程序的输出并处理它/将所需的输入写回进程。为此,您还需要设置 Process/ProcessStartInfo 的更多属性:

string cmdText = @"/c regsvr32 vbscript.dll";
System.Diagnostics.Process temp = new System.Diagnostics.Process();
temp.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
temp.StartInfo.CreateNoWindow = true;
temp.StartInfo.Arguments = cmdText;
temp.StartInfo.FileName = "cmd.exe";
temp.StartInfo.RedirectStandardOutput=true;
temp.StartInfo.RedirectStandardInput=true;
temp.StartInfo.UseShellExecute=false;
temp.Start();

// Read program's output
StringBuilder sb = new StringBuilder();
while (!temp.StandardOutput.EndOfStream)
{
char[] buffer = new char[1024];
temp.StandardOutput.Read(buffer, 0, buffer.Length);
sb.Append(buffer);

// Check output string and write something back if needed
if (sb.ToString().Contains("(Yes/No"))
{
temp.StandardInput.WriteLine("Y");
sb.Clear();
}
}
temp.WaitForExit();

关于C#隐藏cmd窗口需要输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39888244/

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