闲来没事,学习了一下c#,之前从来没有使用它,只知道他好像跟java是对立的,有很多的东西与java的理念比较接近。
今天要解决的一个问题是,如何使用C#去调用windows平台上的cmd来执行一些命令行。
说到执行命令行,必须要使用的就是Process类,它是一个非常有用的类,它十分方便的利用第三方的程序扩展了C#的功能。
以下是可以执行的代码,在vs2005上试验通过,实现的是获得router的mac地址。
今天要解决的一个问题是,如何使用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);
}
}
}