Parsing windows 'ipconfig /all' output

前端 未结 3 678
天命终不由人
天命终不由人 2021-01-27 03:40

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

相关标签:
3条回答
  • 2021-01-27 04:21

    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 () ;
    }
    
    0 讨论(0)
  • 2021-01-27 04:34

    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:

    • Retrieve information about TCP/IP configuration using ipconfig
    • Parse the output from this tool using regex

    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.

    0 讨论(0)
  • 2021-01-27 04:42

    Surely you can get all this information by using NetworkInterface.GetAllNetworkInterfaces()

    0 讨论(0)
提交回复
热议问题