我想做的就是发送一个命令,用 program.exe 打开一个模型 应该 super 简单!
例如:
"C:\Program Files (x86)\River Logic\Enterprise Optimizer 7.4 Developer\EO74.exe" "C:\PauloXLS\Constraint Sets_1.cor"
如果将上面的行粘贴到命令提示符窗口中,效果很好。 但是,当尝试在我的代码中传递完全相同的字符串时,它会卡在 C:\Program
string EXE = "\"" + @tbx_base_exe.Text.Trim() + "\"";
string Model = "\"" + @mdl_path.Trim()+ "\"";
string ExeModel = EXE + " " + Model;
MessageBox.Show(ExeModel);
ExecuteCommand(ExeModel);
ExeModel 在 Visual Studio 上显示以下行:
"\"C:\\Program Files (x86)\\River Logic\\Enterprise Optimizer 7.4 Developer\\EO74.exe\" \"C:\\PauloXLS\\Constraint Sets_1.cor\""
在我看来,这是我需要发送到以下方法的字符串:
public int ExecuteCommand(string Command)
{
int ExitCode;
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = true;
Process = Process.Start(ProcessInfo);
Process.WaitForExit();
ExitCode = Process.ExitCode;
Process.Close();
return ExitCode;
}
我尝试过的事情:
- 一次只传递一个命令(按预期工作),但不是一个选项,因为模型文件将使用另一个版本的软件打开。
- 试图修剪
- 尝试用@和\"
谁能看出任何明显的错误?谢谢。
最佳答案
这很简单。您只需创建一个命令行对象然后写入它,然后执行它您使用 SR.ReadToEnd() 从它读回:
private string GETCMD()
{
string tempGETCMD = null;
Process CMDprocess = new Process();
System.Diagnostics.ProcessStartInfo StartInfo = new System.Diagnostics.ProcessStartInfo();
StartInfo.FileName = "cmd"; //starts cmd window
StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
StartInfo.CreateNoWindow = true;
StartInfo.RedirectStandardInput = true;
StartInfo.RedirectStandardOutput = true;
StartInfo.UseShellExecute = false; //required to redirect
CMDprocess.StartInfo = StartInfo;
CMDprocess.Start();
System.IO.StreamReader SR = CMDprocess.StandardOutput;
System.IO.StreamWriter SW = CMDprocess.StandardInput;
SW.WriteLine("@echo on");
SW.WriteLine("cd\\"); //the command you wish to run.....
SW.WriteLine("cd C:\\Program Files");
//insert your other commands here
SW.WriteLine("exit"); //exits command prompt window
tempGETCMD = SR.ReadToEnd(); //returns results of the command window
SW.Close();
SR.Close();
return tempGETCMD;
}
关于c# - 使用 C# 执行命令行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5182824/