使用Process调用dos命令

来源:互联网 发布:尊荣财富网络借贷 编辑:程序博客网 时间:2024/06/09 17:23

The simplest way to run a command is:

System.Diagnostics.Process.Start ("cmd", @"/c copy c:/myfolder/*.* c:/mybackup");

You can get creative using System.Diagnostics.ProcessStartInfo... for instance you can have your command run without showing a window and capturing the output of the command to process it as you prefer (for instance, displaying it in your console). A simple example of this follows:

// create the ProcessStartInfo using "cmd" as the program to be run, and "/c dir" as the parameters.
// Incidentally, /c tells cmd that we want it to execute the command that follows, and then exit.
// To have more information, start cmd and type help cmd.
System.Diagnostics.ProcessStartInfo sinf =

new System.Diagnostics.ProcessStartInfo ("cmd", "/c dir");
// The following commands are needed to redirect the standard output. This means that it will be redirected to the Process.StandardOutput StreamReader.
sinf.RedirectStandardOutput =
true;
sinf.UseShellExecute =
false;
// Do not create that ugly black window, please...
sinf.CreateNoWindow =
true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process p =
new System.Diagnostics.Process ();
p.StartInfo = sinf;
p.Start (); // well, we should check the return value here...
// We can now capture the output into a string...

string res = p.StandardOutput.ReadToEnd ();
// And do whatever we want with that.
Console.WriteLine (res);
原创粉丝点击