C#操作服务器(4):C#调用cmd安装、启动、停止IIS
作者:陆金龙
发表时间:2015-05-19 22:24
C#调用cmd操作IIS,与调用普通的控制台程序还是有些不一样。
这里只是以操作iis的操作为例,事实上,以下的方法等效于执行在cmd窗体中输入的命令。
代码清单:
public static void ExecutCmdByWriteLine(string strCmd) { using (Process p = new Process()) { p.StartInfo.FileName = "cmd.exe"; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = true; p.Start(); p.StandardInput.WriteLine(strCmd); p.StandardInput.WriteLine("exit"); p.PriorityClass = ProcessPriorityClass.Normal; } } public static string ExecutCmdByArgs(string strCmd) { string strRst = string.Empty; using (Process p = new Process()) { p.StartInfo.FileName = "cmd.exe"; p.StartInfo.Arguments = "/c" + strCmd; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = true; p.Start(); strRst = p.StandardOutput.ReadToEnd();//等待执行完成,获取返回信息 p.StandardInput.WriteLine("exit"); return strRst; } }
使用示例:
方式一:执行过程相当于先启动cmd程序的dos命令窗口,然后输入命令执行
ExecutCmdByWriteLine("iisreset /stop"); //停止iis
ExecutCmdByWriteLine("iisreset /start"); //启动iis
方式二:将cmd.exe做为一个普通个控制台程序调用,方法中传入的参数,做为cmd.exe的参数/c 的值
string strCmd = @"START /w PKGMGR.EXE /l:log.etw /iu:IIS-WebServerRole;IIS-WebServer;IIS-CommonHttpFeatures;IIS-StaticContent;IIS-DefaultDocument;IIS-DirectoryBrowsing;IIS-HttpErrors;IIS-ApplicationDevelopment;IIS-ISAPIExtensions;IIS-ISAPIFilter;IIS-HealthAndDiagnostics;IIS-HttpLogging;IIS-RequestMonitor;IIS-HttpCompressionStatic;IIS-WebServerManagementTools;IIS-ManagementScriptingTools;IIS-IIS6ManagementCompatibility;IIS-Metabase;IIS-ASPNET;IIS-NetFxExtensibility;IIS-ManagementService";
ExecutCmdByArgs(strCmd ); //安装iis
ExecutCmdByArgs("iisreset /stop"); //停止iis
ExecutCmdByArgs("iisreset /start"); //启动iis