Execute CMD command from code

后端 未结 10 1129
故里飘歌
故里飘歌 2020-11-30 06:38

In C# WPF: I want to execute a CMD command, how exactly can I execute a cmd command programmatically?

相关标签:
10条回答
  • 2020-11-30 07:08

    As mentioned by the other answers you can use:

      Process.Start("notepad somefile.txt");
    

    However, there is another way.

    You can instance a Process object and call the Start instance method:

      Process process = new Process();
      process.StartInfo.FileName = "notepad.exe";
      process.StartInfo.WorkingDirectory = "c:\temp";
      process.StartInfo.Arguments = "somefile.txt";
      process.Start();
    

    Doing it this way allows you to configure more options before starting the process. The Process object also allows you to retrieve information about the process whilst it is executing and it will give you a notification (via the Exited event) when the process has finished.

    Addition: Don't forget to set 'process.EnableRaisingEvents' to 'true' if you want to hook the 'Exited' event.

    0 讨论(0)
  • 2020-11-30 07:12

    if you want to start application with cmd use this code:

    string YourApplicationPath = "C:\\Program Files\\App\\MyApp.exe"   
    ProcessStartInfo processInfo = new ProcessStartInfo();
    processInfo.WindowStyle = ProcessWindowStyle.Hidden;
    processInfo.FileName = "cmd.exe";
    processInfo.WorkingDirectory = Path.GetDirectoryName(YourApplicationPath);
    processInfo.Arguments = "/c START " + Path.GetFileName(YourApplicationPath);
    Process.Start(processInfo);
    
    0 讨论(0)
  • 2020-11-30 07:19

    Using Process.Start:

    using System.Diagnostics;
    
    class Program
    {
        static void Main()
        {
            Process.Start("example.txt");
        }
    }
    
    0 讨论(0)
  • 2020-11-30 07:19

    How about you creat a batch file with the command you want, and call it with Process.Start

    dir.bat content:

    dir
    

    then call:

    Process.Start("dir.bat");
    

    Will call the bat file and execute the dir

    0 讨论(0)
提交回复
热议问题