最近做Windows Server 安装工具时,调用cmd 安装的过程:
/// <summary>
/// 执行cmd命令
/// </summary>
/// <param name="fwkPath">.Net Framework 安装路径</param>
/// <param name="installPath">Windows 服务安装路径</param>
/// <param name="isinstall">安装、卸载标识(true标识安装,false标识卸载)</param>
protected void InstallParmas(string fwkPath, Dictionary<string, string> installPath, bool isinstall)
{
if (installPath == null || installPath.Count == 0)
{
MessageBox.Show("请指定 Windows 服务安装文件(.exe)路径!");
return;
}
string path = string.Empty;
int count = 0;
install.Enabled = false;
uninstall.Enabled = false;
try
{
#region cmd执行
/*
* 当前用户是管理员的时候,直接启动应用程序
* 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
*/
//获得当前登录的Windows用户标示
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
ProcessStartInfo startInfo = new ProcessStartInfo();
//判断当前登录用户是否为管理员
if (!principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
startInfo.Verb = "RunAs"; //设置启动动作,确保以管理员身份运行
MessageBox.Show("当前已经设为管理员身份运行!");
}
startInfo.FileName = "cmd.exe ";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.CreateNoWindow = true;
//启动信息
//1.输入cmd命令 set path=C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319 (默认路径)
if (string.IsNullOrEmpty(fwkPath))
{
fwkPath = "set path=C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319";
}
//2.输入cmd命令 windows 的 exe的绝对路径
if (isinstall)
{
foreach (KeyValuePair<string, string> kv1 in installPath)
{
path = "installutil.exe " + kv1.Key;
Process p = new Process();
p.StartInfo = startInfo;
p.Start();
p.StandardInput.WriteLine(fwkPath);
p.StandardInput.WriteLine(path);
//cmd输入退出
p.StandardInput.WriteLine("exit");
//退出cmd窗口
p.WaitForExit();
p.Close();
p.Dispose();
count++;
}
}
else
{
foreach (KeyValuePair<string, string> kv2 in installPath)
{
path = "installutil.exe /u " + kv2.Key;
Process p = new Process();
p.StartInfo = startInfo;
p.Start();
p.StandardInput.WriteLine(fwkPath);
p.StandardInput.WriteLine(path);
//cmd输入退出
p.StandardInput.WriteLine("exit");
//退出cmd窗口
p.WaitForExit();
p.Close();
p.Dispose();
count++;
}
}
/*
string strOutput = string.Empty;
strOutput = p.StandardOutput.ReadToEnd();
//弹出cmd命令信息
MessageBox.Show(strOutput);
*/
#endregion
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
install.Enabled = true;
uninstall.Enabled = true;
}
finally
{
if (isinstall)
{
uninstall.Enabled = true;
MessageBox.Show("安装完成:" + count + "个!");
}
else
{
install.Enabled = true;
MessageBox.Show("卸载完成:" + count + "个!");
}
}
}