目前做的项目中有一个功能是管理员能够手动的备份数据库(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;
}