How to execute command on cmd from C# [closed]

半城伤御伤魂 提交于 2020-01-13 02:40:49

问题


I want to run commands on the cmd from my C# app.

I tried:

string strCmdText = "ipconfig";
        System.Diagnostics.Process.Start("CMD.exe", strCmdText);  

result:

the cmd window pop but the command didn't do nothing.

why?


回答1:


Use

System.Diagnostics.Process.Start("CMD.exe", "/C ipconfig");  

If you want to have cmd still opened use:

System.Diagnostics.Process.Start("CMD.exe", "/K ipconfig");  



回答2:


from codeproject

 public void ExecuteCommandSync(object command)
    {
         try
         {
             // create the ProcessStartInfo using "cmd" as the program to be run,
             // and "/c " as the parameters.
             // Incidentally, /c tells cmd that we want it to execute the command that follows,
             // and then exit.
        System.Diagnostics.ProcessStartInfo procStartInfo =
            new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

        // The following commands are needed to redirect the standard output.
        // This means that it will be redirected to the Process.StandardOutput StreamReader.
        procStartInfo.RedirectStandardOutput = true;
        procStartInfo.UseShellExecute = false;
        // Do not create the black window.
        procStartInfo.CreateNoWindow = true;
        // Now we create a process, assign its ProcessStartInfo and start it
        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo = procStartInfo;
        proc.Start();
        // Get the output into a string
        string result = proc.StandardOutput.ReadToEnd();
        // Display the command output.
        Console.WriteLine(result);
          }
          catch (Exception objException)
          {
          // Log the exception
          }
    }


来源:https://stackoverflow.com/questions/15878810/how-to-execute-command-on-cmd-from-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!