Execute CMD command from code

2019-01-07 16:21发布

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

9条回答
祖国的老花朵
2楼-- · 2019-01-07 16:25

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 !!

查看更多
干净又极端
3楼-- · 2019-01-07 16:31

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");
查看更多
一纸荒年 Trace。
4楼-- · 2019-01-07 16:33

Argh :D not the fastest

Process.Start("notepad C:\test.txt");
查看更多
SAY GOODBYE
5楼-- · 2019-01-07 16:34

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

Process.Start("cmd");
查看更多
Explosion°爆炸
6楼-- · 2019-01-07 16:38

Using Process.Start:

using System.Diagnostics;

class Program
{
    static void Main()
    {
        Process.Start("example.txt");
    }
}
查看更多
【Aperson】
7楼-- · 2019-01-07 16:41

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

查看更多
登录 后发表回答