C#执行cmd

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; 
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值