源动力

程序在于积累和思考
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#中调用Process执行CMD命令

Posted on 2012-03-31 09:05  老K的幸福生活  阅读(4531)  评论(1编辑  收藏  举报

C#中调用命令行执行命令行命令,例如在WinForm程序启动时为了防止数据库没有启动,先启动数据库服务。其中需要主要提一点的就是,在有些电脑上启动的CMD程序的默认路径没有在C盘等系统能找到的路径,在这种情况下,批处理就会失败。所以加了强制转换到C盘的操作,以增加程序的容错性和更多的实用性。程序如下:

/// <summary>
/// 执行批处理
/// </summary>
private void ExecuteBatch()
{
        Process p = new Process();
            p.StartInfo.FileName = @"C:\WINDOWS\system32\cmd.exe ";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.WriteLine(@"c: ");  //先转到系统盘下
            p.StandardInput.WriteLine(@"cd C:\WINDOWS\system32 ");  //再转到CMD所在目录下
            p.StandardInput.WriteLine(@"net start MSSQLSERVER ");
            p.StandardInput.WriteLine("exit");
            p.WaitForExit();
            p.Close();
            p.Dispose();

}