Execute CMD command from code

后端 未结 10 1128
故里飘歌
故里飘歌 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 06:53

    Argh :D not the fastest

    Process.Start("notepad C:\test.txt");
    
    0 讨论(0)
  • 2020-11-30 06:54

    You can do like below:

    var command = "Put your command here";
    System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
    procStartInfo.RedirectStandardOutput = true;
    procStartInfo.UseShellExecute = false;
    procStartInfo.WorkingDirectory = @"C:\Program Files\IIS\Microsoft Web Deploy V3";
    procStartInfo.CreateNoWindow = true; //whether you want to display the command window
    System.Diagnostics.Process proc = new System.Diagnostics.Process();
    proc.StartInfo = procStartInfo;
    proc.Start();
    string result = proc.StandardOutput.ReadToEnd();
    label1.Text = result.ToString();
    
    0 讨论(0)
  • 2020-11-30 06:59

    Are you asking how to bring up a command windows? If so, you can use the Process object ...

    Process.Start("cmd");
    
    0 讨论(0)
  • 2020-11-30 07:06

    In addition to the answers above, you could use a small extension method:

    public static class Extensions
    {
       public static void Run(this string fileName, 
                              string workingDir=null, params string[] arguments)
        {
            using (var p = new Process())
            {
                var args = p.StartInfo;
                args.FileName = fileName;
                if (workingDir!=null) args.WorkingDirectory = workingDir;
                if (arguments != null && arguments.Any())
                    args.Arguments = string.Join(" ", arguments).Trim();
                else if (fileName.ToLowerInvariant() == "explorer")
                    args.Arguments = args.WorkingDirectory;
                p.Start();
            }
        }
    }
    

    and use it like so:

    // open explorer window with given path
    "Explorer".Run(path);   
    
    // open a shell (remanins open)
    "cmd".Run(path, "/K");
    
    0 讨论(0)
  • 2020-11-30 07:07

    Here's a simple example :

    Process.Start("cmd","/C copy c:\\file.txt lpt1");
    
    0 讨论(0)
  • 2020-11-30 07:07

    You can use this to work cmd in C#:

    ProcessStartInfo proStart = new ProcessStartInfo();
    Process pro = new Process();
    proStart.FileName = "cmd.exe";
    proStart.WorkingDirectory = @"D:\...";
    string arg = "/c your_argument";
    proStart.Arguments = arg;
    proStart.WindowStyle = ProcessWindowStyle.Hidden;
    pro.StartInfo = pro;
    pro.Start();
    

    Don't forget to write /c before your argument !!

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