Parsing windows 'ipconfig /all' output

前端 未结 3 677
天命终不由人
天命终不由人 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: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.

提交回复
热议问题