c# - 使用 C# 执行命令行

标签 c# c#-4.0 cmd command-prompt

我想做的就是发送一个命令,用 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;
}

我尝试过的事情:

  1. 一次只传递一个命令(按预期工作),但不是一个选项,因为模型文件将使用另一个版本的软件打开。
  2. 试图修剪
  3. 尝试用@和\"

谁能看出任何明显的错误?谢谢。

最佳答案

这很简单。您只需创建一个命令行对象然后写入它,然后执行它您使用 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/

相关文章:

c# - 标识自动增量未应用于列

c# - 如何获取计数并弹出消息框

c# - 改进 LINQ 查询返回满足特定条件的项目的索引

Java 堆空间 Xmx Xms 参数忽略

c# - 什么是标准的 Akka.Net 消息命令验证模式?

c# - 验证 double /小数是否为货币 C#

c# - 如何处理非标准 Json 日期

c# - CreateObject 等效于 C# 4、动态关键字和后期绑定(bind)?

java - 如何通过Java swing执行cmd命令

java - 为什么我不能在CMD上编译这个简单的Java代码,而是在在线编译器上编译它?