在C# WPF中:我想执行一个CMD命令,如何在程序中编程执行CMD命令?
这里有一个简单的例子:
Process.Start("cmd","/C copy c:\\file.txt lpt1");
正如其他答案所提到的,您可以使用:
Process.Start("notepad somefile.txt");
然而,还有另一种方法。
您可以实例化一个Process对象并调用Start实例方法:
Process process = new Process();
process.StartInfo.FileName = "notepad.exe";
process.StartInfo.WorkingDirectory = "c:\temp";
process.StartInfo.Arguments = "somefile.txt";
process.Start();
这样做可以让您在启动进程之前配置更多选项。Process对象还允许您在执行过程中检索有关进程的信息,并在进程完成时通过Exited事件通知您。
另外,如果想要挂钩Exited事件,请不要忘记将 'process.EnableRaisingEvents' 设置为 'true'。
如果您想使用命令提示符启动应用程序,请使用此代码:
如果你想要用cmd启动一个应用程序,使用这段代码:
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);
using System.Diagnostics;
class Program
{
static void Main()
{
Process.Start("example.txt");
}
}
dir
接下来调用:
Process.Start("dir.bat");
将调用批处理文件并执行dir命令
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();
哎呀:D,速度不是最快的
Process.Start("notepad C:\test.txt");
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();
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();
}
}
}
然后像这样使用它:
// open explorer window with given path
"Explorer".Run(path);
// open a shell (remanins open)
"cmd".Run(path, "/K");