I am having a bit of trouble parsing the output of \'ipconfig /all\' using a regex. Currently I am using RegexBuddy for testing, but I want to use the regex in C#.NET.
M
Why use regex? Your input is in simple key-value format. Use something along the lines of
foreach (var line in lines)
{
var index = line.IndexOf (':') ;
if (index <= 0) continue ; // skip empty lines
var key = line.Substring (0, index).TrimEnd (' ', '.') ;
var value = line.Substring (index + 1).Replace ("(Preferred)", "").Trim () ;
}
but I want to use the regex in C#.NET.
Why Regex? Believe me, you don't want to use regex. A wise man once said:
Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems.
Let me state your 2 problems right now:
Actually you could retrieve this information using WMI directly and thus solve your original problem and never think about using regexes again:
using (var mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
using (var instances = mc.GetInstances())
{
foreach (ManagementObject instance in instances)
{
if (!(bool)instance["ipEnabled"])
{
continue;
}
Console.WriteLine("{0}, {1}, {2}", instance["Caption"], instance["ServiceName"], instance["MACAddress"]);
string[] ipAddresses = (string[])instance["IPAddress"];
string[] subnets = (string[])instance["IPSubnet"];
string[] gateways = (string[])instance["DefaultIPGateway"];
string domains = (string)instance["DNSDomain"];
string description = (string)instance["Description"];
bool dhcp = (bool)instance["DHCPEnabled"];
string[] dnses = (string[])instance["DNSServerSearchOrder"];
}
}
In addition to that you could create strongly typed wrapper for those WMI classes using the Mgmtclassgen.exe utility making your code even safer and you will be able tpo get rid of the magic strings.
Surely you can get all this information by using NetworkInterface.GetAllNetworkInterfaces()