封装调用cmd的命令
上一篇 /
下一篇 2010-02-09 19:41:01
/ 个人分类:c#测试
我们经常在测试代码里调用cmd命令,比如调用ping命令查看网络是否畅通,net use命令获取访问某台机器的操作权限等。可以把它封装成这样。
public static string InvokeCmd(string strCmd)
{
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe");
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.CreateNoWindow = true;
startInfo.Arguments = string.Format(@"/c {0}", strCmd);
process.StartInfo = startInfo;
process.Start();
string message = process.StandardOutput.ReadToEnd();
process.WaitForExit();
process.Close();
return message;
}
下面是调用这个方法的一个例子 (使用ping命令判断一个机器是否处于运行状态)
public static bool IsRunning(string machineName)
{
string message = InvokeCmd(string.Format("ping {0} -n 1", machineName));
if (message.Contains("Reply from"))
{
return true;
}
return false;
}
收藏
举报
TAG: