首页 > 其他 > 详细

C#执行cmd

时间:2014-03-30 14:19:36      阅读:515      评论:0      收藏:0      [点我收藏+]
using System;// 要用使用Process类来创建独立的进程,导入
using System.Collections.Generic;
using System.Text;


using System.Diagnostics; //诊断


namespace Cmd
{


class CmdConsole
{


[STAThread]
static void Main(string[] args)
{
Console.Write("输入要执行的命令");
string ip = Console.ReadLine();
string strRst = CmdPing(ip);
Console.WriteLine(strRst);
Console.ReadLine();
}


private static
string CmdPing(string strIp)
{
// 实例一个Process类,启动一个独立进程
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 = true;
// 启动进程
string pingrst;
p.Start();
p.StandardInput.WriteLine(strIp);
p.StandardInput.WriteLine("exit");
// 从输出流获取命令执行结果
string strRst = p.StandardOutput.ReadToEnd();
pingrst = strRst;
// if end
p.Close();
return pingrst;
}
}
}


有些时候运行系统命令可以很方便的达到一些特定目的。比如说,可以用c:\>powercfg /H on来启用系统休眠。c:\>netsh firewall set opmode DISABLE可以用来禁用系统防火墙。


首先,在C#中运行一个外部程序是非常简单的: System.Diagnostics.Process.Start("cmd.exe", "/K dir");


该命令会弹出一个命令行窗口并 列出当前目录中的文件。把/K改成/C可以自动关闭弹出的命令行窗口,不过黑窗口还是一闪而过,而且我们看不到运行结果。


对 于我们漂亮的WinForm窗口,跳出黑黑的DOS窗口总是非常丑陋和让人不爽的。如何既能运行系统命令,又能拿到结果,而且还不显示丑陋的命令行窗口 呢?解决方法就是Process类中StartInfo成员。StartInfo成员可以指定弹出窗口是最小化,最大化,或是隐藏窗口。更妙的是,我们可 以通过设定StartInfo.CreateNoWindow=false,让该进程没有任何关联窗口!同时,我们接管该进程的标准输入和输出。设定 StartInfo.RedirectStandardOutput为真,然后从Process.StandartOutput读取运行结果。  


以下是一个逐步的示范,可以显示你机器当前的IP配置:


一、用VS2005或者C# Express建立一个Winform程序。


二、添加一个按钮和一个RichTextBox。


三、在设计界面双击添加的按钮,自动生成button1_Click事件响应代码。


四、把button1_Click代码换成以下所附代码。


五、编译并运行,大致运行结果可见所附的图片。


private void button1_Click(object sender, EventArgs e) 
{
System.Diagnostics.Process proc = new Process();
proc.StartInfo.FileName = "netsh.exe"; 
proc.StartInfo.Arguments = "interface ipv4 show config";


proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false; 
proc.StartInfo.RedirectStandardOutput = true;


this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
proc.Start(); 
using (StreamReader reader = proc.StandardOutput)

string line = reader.ReadLine(); 
while (line != null)

richTextBox1.AppendText(line + " "); 
Application.DoEvents(); 
line = reader.ReadLine(); 


proc.WaitForExit(); 
this.Cursor = Cursors.Default; 
}

C#执行cmd,布布扣,bubuko.com

C#执行cmd

原文:http://blog.csdn.net/ddgweb/article/details/22576279

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!