[英]How to send commands to cmd in C#
我正在使用C#编写程序,我需要打开cmd.exe,发送命令并获得答案。 我四处搜索并找到一些答案来使用diagnostics.process。
现在,我有两个问题:
另一方面,我只找到了如何通过参数和process.standardInput.writeline()
将命令发送到cmd.exe。 有没有更方便的方法使用。 我需要在cmd.exe打开时发送命令。
我发送的代码的一部分可能会有所帮助:
System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
myProcess.StartInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe");
//myProcess.StartInfo.Arguments = "/c g95";
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.RedirectStandardError = true;
myProcess.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(myProcess_OutputDataReceived);
myProcess.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(myProcess_ErrorDataReceived);
myProcess.Start();
myProcess.BeginOutputReadLine();
myProcess.BeginErrorReadLine();
myProcess.StandardInput.WriteLine("g95 c:\\1_2.f -o c:\\1_2.exe");
您可以直接指定g95
并将所需的命令行参数传递给它。 您不需要先执行cmd
。 可能无法识别该命令,因为未加载用户配置文件中的设置。 尝试将StartInfo
的属性LoadUserProfile
设置为true。
myProcess.StartInfo.LoadUserProfile = true;
这也应该正确设置path
变量。 您的代码看起来像这样:
Process myProcess = new Process();
myProcess.StartInfo = new ProcessStartInfo("g95");
myProcess.StartInfo.Arguments = "c:\\1_2.f -o c:\\1_2.exe"
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.LoadUserProfile = true;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.RedirectStandardError = true;
myProcess.OutputDataReceived += myProcess_OutputDataReceived;
myProcess.ErrorDataReceived += myProcess_ErrorDataReceived;
myProcess.Start();
myProcess.BeginOutputReadLine();
myProcess.BeginErrorReadLine();
你收到了错误
“g95不被认为是内部或外部......”
因为您尚未在PATH环境变量中添加g95.exe的路径。 如果打开命令提示符并键入g95,您将得到类似的结果。 这是一个解释它的G95 Windows FAQ页面的链接 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.