C#中调用windows的cmd命令

闲来没事,学习了一下c#,之前从来没有使用它,只知道他好像跟java是对立的,有很多的东西与java的理念比较接近。
今天要解决的一个问题是,如何使用C#去调用windows平台上的cmd来执行一些命令行。
说到执行命令行,必须要使用的就是Process类,它是一个非常有用的类,它十分方便的利用第三方的程序扩展了C#的功能。

以下是可以执行的代码,在vs2005上试验通过,实现的是获得router的mac地址。



using System;
using System.Collections.Generic;
using System.Text;

using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
//实例化process对象
System.Diagnostics.Process p = new System.Diagnostics.Process();
//要执行的程序名称,cmd
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
//可能接受来自调用程序的输入信息
p.StartInfo.RedirectStandardInput = true;
//由调用程序获取输出信息
p.StartInfo.RedirectStandardOutput = true;
//不显示程序窗口
p.StartInfo.CreateNoWindow = true;
p.Start();//启动程序
//向CMD窗口发送输入信息:
p.StandardInput.WriteLine("arp -a");
//不过不要忘记加上Exit,不然程序会异常退出
p.StandardInput.WriteLine("exit");
//获取CMD窗口的输出信息:
string sOutput = p.StandardOutput.ReadToEnd();

//使用正则再过滤一下,获得mac地址
String mac = "";
// 定义一个Regex对象实例,存储mac的正则
Regex r = new Regex("([a-z0-9]{2}-){5}[a-z0-9]{2}");
MatchCollection mc = r.Matches(sOutput);
//在输入字符串中找到所有匹配
for (int i = 0; i < mc.Count; i++)
{
mac = mc[i].Value; //将匹配的字符串添在字符串数组中
}

Console.WriteLine(mac);
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值