我正在使用C#编写程序,我需要打开cmd.exe,发送命令并获得答案.
我四处搜索并找到一些答案来使用diagnostics.process.
现在,我有两个问题:
>当我得到进程的输出时,输出不会显示在cmd consoule本身上.
>我需要在系统上调用g95编译器.当我从cmd手动调用它时,它被调用并且运行良好,但是当我以编程方式调用它时,我有这样的错误:“g95不被识别为内部或外部……”
另一方面,我只找到了如何通过参数和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;
这也应该正确设置路径变量.
您的代码看起来像这样:
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();