C#执行cmd.exe 不能关闭问题

        目前做的项目中有一个功能是管理员能够手动的备份数据库(sqlserver 2012)。第一种方法便是用sqlserver的 backup 命令来实现。在这里就需要用csharp调用命令行来实现。在网上看到的方法全都是这种(用cmd工具来执行命令)

 /// <summary>
    /// 运行CMD命令
    /// </summary>
    /// <param name="cmd">命令</param>
    /// <param name="showWindow">是否显示执行窗体</param>
    /// <returns></returns>
    public static string ExecuteCmd(string[] cmd, bool showWindow)
    {
      Process p = new Process();
      p.StartInfo.FileName = "cmd.exe";
      //关闭shell的使用
      p.StartInfo.UseShellExecute = false;
      //重定向标准输入
      p.StartInfo.RedirectStandardInput = true;
      //重定向标准输出
      p.StartInfo.RedirectStandardOutput = true;
      //重定向标准错误
      p.StartInfo.RedirectStandardError = true;
      //是否显示窗体
      p.StartInfo.CreateNoWindow = !showWindow;
      p.Start();
      
      p.StandardInput.AutoFlush = true;
      for (int i = 0; i < cmd.Length; i++)
      {
        p.StandardInput.WriteLine(cmd[i].ToString());
      }
      p.StandardInput.WriteLine("exit");
      string strRst = p.StandardOutput.ReadToEnd();
      p.WaitForExit();
      p.Close();
      p.Dispose();
      return strRst;
    }

我觉得上面这种有个不好之处  当所执行的命名(程序)不是执行完就关闭(如 ftp osql 等命令)的时候就会出现cmd这个进程无法关闭导致程序卡死。

于是还不如直接执行该执行的程序(ftp.exe  osql.exe )下面是我的方法

<span style="white-space:pre">	</span>/// <summary>
       /// 通过命令行方式执行 程序
       /// </summary>
       /// <param name="app">程序名</param>
       /// <param name="argments">程序参数</param>
       /// <param name="cmd">进入程序后的命令</param>
       /// <param name="showWindow">是否显示窗口</param>
       /// <returns>命令行执行完后内容</returns>
        public static string ExecuteCmd(string app,string argments,string[] cmd, bool showWindow)
        {
            Process p = new Process();
            p.StartInfo.FileName = app;
            p.StartInfo.Arguments = argments;
            //关闭shell的使用
            p.StartInfo.UseShellExecute = false;
            //重定向标准输入
            p.StartInfo.RedirectStandardInput = true;
            //重定向标准输出
            p.StartInfo.RedirectStandardOutput = true;
            //重定向标准错误
            p.StartInfo.RedirectStandardError = true;
            //是否显示窗体
            p.StartInfo.CreateNoWindow = !showWindow;
            p.Start();
            p.StandardInput.AutoFlush = true;
            for (int i = 0; i < cmd.Length; i++)
            {
                p.StandardInput.WriteLine(cmd[i].ToString());
            }
            string strRst = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            p.Close();
            p.Dispose();
            return strRst;
        }


 
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值