Process p = new Process();
p.StartInfo.FileName = "cmd";
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
StreamWriter sw = p.StandardInput;
sw.WriteLine("d:");
sw.WriteLine(@"cd d:\test");
sw.WriteLine(@"copy *.* c:\test");
sw.Close();
Process p = new Process(); p.StartInfo.FileName = "cmd"; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.Start(); StreamWriter sw = p.StandardInput; sw.WriteLine("d:"); sw.WriteLine(@"cd d:\test"); sw.WriteLine(@"copy *.* c:\test"); sw.Close();显得更好些
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
string strOutput = null;
try
{
p.Start();
p.StandardInput.WriteLine(commandText);
p.StandardInput.WriteLine("exit");
strOutput = p.StandardOutput.ReadToEnd();
p.WaitForExit();
p.Close();
}
catch(Exception e)
{
strOutput = e.Message;
}
return strOutput;
}
参考
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;namespace Test
{
class Program
{
static void Main(string [] args)
{
try
{
Console.WriteLine("请输入命令控制:");
string str = Console.ReadLine();
string [] execute = str.Split(' ');
string path = "test.bat";
string order = string.Empty;
foreach (string s in execute)
{
order += s+" ";
}
order = order.TrimEnd(' ');
Process p = new Process();
ProcessStartInfo pi = new ProcessStartInfo(path, order);
p.StartInfo = pi;
p.Start();
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
}
}
}
在应用程序起始目录创建test.bat文件,内容如下:
@echo off
::如果要调试bat命令行代码 将开关打开 修改为:@echo on
if not "%1"=="1" echo 您没有选择关机
if "%1"=="1" shutdown -s -t 200
pause
if %2==0 shutdown -a
echo 系统已取消自动关机
pause
echo 下面,系统将输出第三个参数的值
echo %3
echo 如果第三个参数为"xcopy",系统则copy第四个参数指定的文件至第五个参数内:
pause
if %3==xcopy %3 %4 %5
::echo 复制完成
if not "%3"=="xcopy" echo 您没有选择执行复制命令
pause
echo 示例结束,谢谢!
pause
转自:http://blog.csdn.net/yulusilian1/archive/2008/11/19/3335470.aspx