Use C# to build a network card configuration tool (Visual Studio 2022)

1 Preface

Recently, due to some business requirements, it is necessary to use an IP address configuration management tool used on Windows platform. This paper records some problems and solutions encountered in the development process, with relevant C# logic processing codes. The project was written using the WPF framework.

2 development environment

Operating system: Windows 10
Development tool: Visual Studio 2022
Target environment: Windows 10/Windows 7
Development requirements: out of the box

3 code logic

3.1 obtaining network card information

private static List<NetworkInterface> GetNetworkInfo()
{
    List<NetworkInterface> result = new List<NetworkInterface>();
    foreach(NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
    {
        result.Add(adapter);
    }
    return  result;
}

Using this function, you can get a list composed of NetworkInterface. The NetworkInterface class returns the Name, Id, Description, etc. of the network card. The three members of the appeal will be used in the following functions.

3.2 set and display network card information (IP, DNS, DHCP, subnet mask, MAC address)

private void SetAdapterInfo(NetworkInterface adapter)
{
    IPInterfaceProperties ip = adapter.GetIPProperties();
    UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
    foreach (UnicastIPAddressInformation item in ipCollection)
    {
    	//IPv4 filtering
        if (item.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
        {
        	//IpAddress and subnetMask are TextBox classes, UI display;
            IpAddress.Text = item.Address.ToString();
            subnetMask.Text = item.IPv4Mask.ToString();
        }
    }
    //DNS
    if (ip.DnsAddresses.Count > 0)
    {
    	//DNS and DNS2 are also TextBox class, UI display;
        DNS.Text = ip.DnsAddresses[0].ToString();
        if (ip.DnsAddresses.Count > 1)
        {
            DNS2.Text = ip.DnsAddresses[1].ToString();
        }
        else
        {
            DNS2.Text = "spare DNS non-existent!";
        }
    }
    else
    {
        DNS.Text = "DNS non-existent!";
        DNS2.Text = "spare DNS non-existent!";
    }
    //GateWay is a TextBox class, UI display; GetGateWay is a user-defined function, as shown below;
    Gateway.Text = GetGateWay(ip);
    //DHCP
    if (ip.DhcpServerAddresses.Count > 0)
    {
    	//DHCPServer is a TextBox class, UI display;
        DHCPServer.Text = ip.DhcpServerAddresses.FirstOrDefault().ToString();
    }
    else
    {
        DHCPServer.Text = "DHCP Service does not exist!";
    }
    //MAC
    PhysicalAddress pa = adapter.GetPhysicalAddress();
    byte[] bytes = pa.GetAddressBytes();
    StringBuilder sb = new StringBuilder();
    //XVI prohibited conversion
    for (int i = 0; i < bytes.Length; i++)
    {
        sb.Append(bytes[i].ToString("X2"));
        if (i != bytes.Length - 1)
        {
            sb.Append('-');
        }
    }
    //MAC is a TextBox class, UI display;
    MAC.Text = sb.ToString();
    //IsAutoSelector is a ComBox class, UI display;
    IsAutoSelector.SelectedIndex = 0;
}

Some TextBox class and ComBox class instances are used in the above functions, which are related to UI display. IsAutoSelector is a ComBox that sets whether to configure automatically, 0 is my default setting, and the first display of the ComBoxItem of this ComBox is automatic setting;

//Get gateway
private string GetGateWay(IPInterfaceProperties ip)
{
    string gateWay = "Gateway information does not exist!";
    GatewayIPAddressInformationCollection gateways = ip.GatewayAddresses;
    foreach(GatewayIPAddressInformation gateway in gateways)
    {
        if (IsPingIP(gateway.Address.ToString()))
        {
            gateWay = gateway.Address.ToString();
            break;
        }
    }
    return gateWay;
}
//Ping gateway
private static bool IsPingIP(string ip)
{
    try
    {
        Ping ping = new Ping();
        PingReply reply = ping.Send(ip, 1000);
        if(reply != null) { return true; }else { return false; }
    }catch
    {
        return false;
    }
}

3.3 enable DHCP service (automatically obtain IP, gateway and DNS)

private static void EnableDHCP(NetworkInterface adapter)
{
    ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
    ManagementObjectCollection moc = wmi.GetInstances();
    foreach (ManagementObject m in moc)
    {
        if (!(bool)m["IPEnabled"])
            continue;
        if(m["SettingID"].ToString() == adapter.Id)
        {
            m.InvokeMethod("SetDNSServerSearchOrder", null);
            m.InvokeMethod("EnableDHCP", null);
            MessageBox.Show("Automatic acquisition has been set!");
        }
    }
}

3.4 turn on / off the network card

private static ManagementObject GetNetwork(NetworkInterface adapter)
{
    string netState = "SELECT * From Win32_NetworkAdapter"; //Note that this is Win32_NetworkAdapter, not Win32_NetworkAdapterConfiguration
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(netState);
    ManagementObjectCollection moc = searcher.Get();
    /*MessageBox.Show(adapter.Description);*/
    foreach (ManagementObject m in moc)
    {
        /*MessageBox.Show(m["Name"].ToString());*/
        if(m["Name"].ToString() == adapter.Description) //Note that the Name here corresponds to the Description of the adapter.
        {
            return m;
        }
    }
    return null;
}

private static bool EnableAdapter(ManagementObject m)
{
    try
    {
        m.InvokeMethod("Enable", null);
        return true;
    }
    catch
    {
        return false;
    }
}

private static bool DisableAdapter(ManagementObject m)
{
    try
    {
        m.InvokeMethod("Disable", null);
        return true;
    }
    catch
    {
        return false;
    }
}

3.5 setting IP, DNS and subnet mask

private static bool SetIPAddress(NetworkInterface adapter, string[] ip, string[] submask, string[] gateway, string[] dns)
{
    ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); //Note that this is Win32_NetworkAdapterConfiguration
    ManagementObjectCollection moc = mc.GetInstances();
    string str = "";
    foreach(ManagementObject m in moc)
    {
        /*if (!(bool)m["IPEnabled"])
            continue;*/
        if (m["SettingID"].ToString() == adapter.Id)
        {
        	//IP and subnet mask
            if (ip != null && submask != null)
            {
                ManagementBaseObject inPar;
                ManagementBaseObject outPar;
                string caption = m["Caption"].ToString();
                //Note that this is EnableStatic
                inPar = m.GetMethodParameters("EnableStatic"); 
                //Note that there cannot be null in the ip array;
                inPar["IPAddress"] = ip;
                //Note that there cannot be null in the submask array;
                inPar["SubnetMask"] = submask;
                outPar = m.InvokeMethod("EnableStatic", inPar, null);
                str = outPar["returnvalue"].ToString();
                //0 or 1 indicates that the setting is successful;
                //Return value description website: https://msdn.microsoft.com/en-us/library/aa393301(v=vs.85).aspx
                if (str != "0" && str != "1")
                {
                    return false;
                }
            }
            //gateway
            if (gateway != null)
            {
                ManagementBaseObject inPar;
                ManagementBaseObject outPar;
                string caption = m["Caption"].ToString();
                //Note that this is SetGateways;
                inPar = m.GetMethodParameters("SetGateways");
                //Note that there cannot be null in the gateway array;
                inPar["DefaultIPGateway"] = gateway;
                outPar = m.InvokeMethod("SetGateways", inPar, null);
                str = outPar["returnvalue"].ToString();
                if (str != "0" && str != "1")
                {
                    return false;
                }
            }
            //DNS
            if(dns != null)
            {
                ManagementBaseObject inPar;
                ManagementBaseObject outPar;
                //Note that this is SetDNSServerSearchOrder;
                inPar = m.GetMethodParameters("SetDNSServerSearchOrder");
                //Note that dns array cannot have null;
                inPar["DNSServerSearchOrder"] = dns;
                outPar = m.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
                str = outPar["returnvalue"].ToString();
                if (str != "0" && str != "1")
                {
                    return false;
                }
            }
            return true;
        }
    }
    return false ;
}

3.6 complete code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Management;
using System.Net.NetworkInformation;

namespace nextseq_utils
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly List<NetworkInterface> adapters;

        public MainWindow()
        {
            InitializeComponent();
            adapters = GetNetworkInfo();
            foreach(NetworkInterface adapter in adapters)
            {
                string Name = adapter.Name;
                ComboBoxItem cbi = new ComboBoxItem();
                cbi.Content = Name;
                AdapterSelector.Items.Add(cbi);
            }
        }

        private static List<NetworkInterface> GetNetworkInfo()
        {
            List<NetworkInterface> result = new List<NetworkInterface>();
            foreach(NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
            {
                result.Add(adapter);
            }
            return  result;
        }

        private NetworkInterface GetAdapterByName(string name)
        {
            NetworkInterface adapter = null;
            foreach(NetworkInterface adapter2 in adapters)
            {
                if(adapter2.Name == name)
                {
                    adapter = adapter2;
                    break;
                }
            }
            return adapter;
        }

        private string GetGateWay(IPInterfaceProperties ip)
        {
            string gateWay = "Gateway information does not exist!";
            GatewayIPAddressInformationCollection gateways = ip.GatewayAddresses;
            foreach(GatewayIPAddressInformation gateway in gateways)
            {
                if (IsPingIP(gateway.Address.ToString()))
                {
                    gateWay = gateway.Address.ToString();
                    break;
                }
            }
            return gateWay;
        }

        private static bool IsPingIP(string ip)
        {
            try
            {
                Ping ping = new Ping();
                PingReply reply = ping.Send(ip, 1000);
                if(reply != null) { return true; }else { return false; }
            }catch
            {
                return false;
            }
        }

        private void SetAdapterInfo(NetworkInterface adapter)
        {
            IPInterfaceProperties ip = adapter.GetIPProperties();
            UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
            foreach (UnicastIPAddressInformation item in ipCollection)
            {
                if (item.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    IpAddress.Text = item.Address.ToString();
                    subnetMask.Text = item.IPv4Mask.ToString();
                }
            }
            if (ip.DnsAddresses.Count > 0)
            {
                DNS.Text = ip.DnsAddresses[0].ToString();
                if (ip.DnsAddresses.Count > 1)
                {
                    DNS2.Text = ip.DnsAddresses[1].ToString();
                }
                else
                {
                    DNS2.Text = "spare DNS non-existent!";
                }
            }
            else
            {
                DNS.Text = "DNS non-existent!";
                DNS2.Text = "spare DNS non-existent!";
            }
            Gateway.Text = GetGateWay(ip);
            if (ip.DhcpServerAddresses.Count > 0)
            {
                DHCPServer.Text = ip.DhcpServerAddresses.FirstOrDefault().ToString();
            }
            else
            {
                DHCPServer.Text = "DHCP Service does not exist!";
            }
            PhysicalAddress pa = adapter.GetPhysicalAddress();
            byte[] bytes = pa.GetAddressBytes();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                sb.Append(bytes[i].ToString("X2"));
                if (i != bytes.Length - 1)
                {
                    sb.Append('-');
                }
            }
            MAC.Text = sb.ToString();
            IsAutoSelector.SelectedIndex = 0;
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string content = AdapterSelector.SelectedValue.ToString();
            content = content.Replace("System.Windows.Controls.ComboBoxItem: ","");
            NetworkInterface adapter = GetAdapterByName(content);
            if(adapter != null)
            {
                SetAdapterInfo(adapter);
            }
        }

        private static void EnableDHCP(NetworkInterface adapter)
        {
            ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = wmi.GetInstances();
            foreach (ManagementObject m in moc)
            {
                if (!(bool)m["IPEnabled"])
                    continue;
                if(m["SettingID"].ToString() == adapter.Id)
                {
                    m.InvokeMethod("SetDNSServerSearchOrder", null);
                    m.InvokeMethod("EnableDHCP", null);
                    MessageBox.Show("Automatic acquisition has been set!");
                }
            }
        }

        private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            string content = IsAutoSelector.SelectedValue.ToString();
            content = content.Replace("System.Windows.Controls.ComboBoxItem: ", "");
            if(content == "automatic")
            {
                IpAddress.IsEnabled = false;
                subnetMask.IsEnabled = false;
                Gateway.IsEnabled = false;
                DNS.IsEnabled = false;
                DNS2.IsEnabled = false;
                DHCPServer.IsEnabled = false;
                SettingIP.IsEnabled = false;
                if (IsAutoSelector.Text == "Manual")
                {
                    string name = AdapterSelector.SelectedValue.ToString();
                    name = name.Replace("System.Windows.Controls.ComboBoxItem: ", "");
                    NetworkInterface adapter = GetAdapterByName(name);
                    if (adapter != null)
                    {
                        EnableDHCP(adapter);
                        SetAdapterInfo(adapter);
                    }
                }
            }
            else if(content == "Manual")
            {
                IpAddress.IsEnabled = true;
                subnetMask.IsEnabled = true;
                Gateway.IsEnabled = true;
                DNS.IsEnabled = true;
                DNS2.IsEnabled = true;
                DHCPServer.IsEnabled = true;
                SettingIP.IsEnabled = true;
            }
        }
    
        private static ManagementObject GetNetwork(NetworkInterface adapter)
        {
            string netState = "SELECT * From Win32_NetworkAdapter";
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(netState);
            ManagementObjectCollection moc = searcher.Get();
            /*MessageBox.Show(adapter.Description);*/
            foreach (ManagementObject m in moc)
            {
                /*MessageBox.Show(m["Name"].ToString());*/
                if(m["Name"].ToString() == adapter.Description)
                {
                    return m;
                }
            }
            return null;
        }

        private static bool EnableAdapter(ManagementObject m)
        {
            try
            {
                m.InvokeMethod("Enable", null);
                return true;
            }
            catch
            {
                return false;
            }
        }

        private static bool DisableAdapter(ManagementObject m)
        {
            try
            {
                m.InvokeMethod("Disable", null);
                return true;
            }
            catch
            {
                return false;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if(AdapterSelector.Text == "")
            {
                MessageBox.Show("Please select a network card before operation!");
            }
            else
            {
                NetworkInterface adapter = GetAdapterByName(AdapterSelector.Text);
                if(adapter != null)
                {
                    if (EnableAdapter(GetNetwork(adapter)))
                    {
                        MessageBox.Show("Network card opened successfully!");
                    }
                    else
                    {
                        MessageBox.Show("Failed to open network card!");
                    };
                }
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (AdapterSelector.Text == "")
            {
                MessageBox.Show("Please select a network card before operation!");
            }
            else
            {
                NetworkInterface adapter = GetAdapterByName(AdapterSelector.Text);
                if (adapter != null)
                {
                    if (DisableAdapter(GetNetwork(adapter)))
                    {
                        MessageBox.Show("Network card closed successfully!");
                    }
                    else
                    {
                        MessageBox.Show("Failed to close network card!");
                    };
                }
            }
        }

        private static bool SetIPAddress(NetworkInterface adapter, string[] ip, string[] submask, string[] gateway, string[] dns)
        {
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            string str = "";
            foreach(ManagementObject m in moc)
            {
                /*if (!(bool)m["IPEnabled"])
                    continue;*/
                if (m["SettingID"].ToString() == adapter.Id)
                {
                    if (ip != null && submask != null)
                    {
                        ManagementBaseObject inPar;
                        ManagementBaseObject outPar;
                        string caption = m["Caption"].ToString();
                        inPar = m.GetMethodParameters("EnableStatic");
                        inPar["IPAddress"] = ip;
                        inPar["SubnetMask"] = submask;
                        outPar = m.InvokeMethod("EnableStatic", inPar, null);
                        str = outPar["returnvalue"].ToString();
                        if (str != "0" && str != "1")
                        {
                            return false;
                        }
                    }
                    if (gateway != null)
                    {
                        ManagementBaseObject inPar;
                        ManagementBaseObject outPar;
                        string caption = m["Caption"].ToString();
                        inPar = m.GetMethodParameters("SetGateways");
                        inPar["DefaultIPGateway"] = gateway;
                        outPar = m.InvokeMethod("SetGateways", inPar, null);
                        str = outPar["returnvalue"].ToString();
                        if (str != "0" && str != "1")
                        {
                            return false;
                        }
                    }
                    if(dns != null)
                    {
                        ManagementBaseObject inPar;
                        ManagementBaseObject outPar;
                        inPar = m.GetMethodParameters("SetDNSServerSearchOrder");
                        inPar["DNSServerSearchOrder"] = dns;
                        outPar = m.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
                        str = outPar["returnvalue"].ToString();
                        if (str != "0" && str != "1")
                        {
                            return false;
                        }
                    }
                    return true;
                }
            }
            return false ;
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            NetworkInterface adapter = GetAdapterByName(AdapterSelector.Text);
            if (adapter != null)
            {
                string[] ip = { IpAddress.Text };
                string[] submask = { subnetMask.Text };
                string[] gateway;
                if(Gateway.Text != "Gateway information does not exist!" && Gateway.Text != "")
                {
                    gateway = new string[1];
                    gateway[0] = Gateway.Text;
                }
                else
                {
                    gateway = null;
                }
                string[] dns; 
                if(DNS.Text != "DNS non-existent!" && DNS.Text != "")
                {
                    
                    if(DNS2.Text != "spare DNS non-existent!" && DNS2.Text != "")
                    {
                        dns = new string[2];
                        dns[0] = DNS.Text;
                        dns[1] = DNS2.Text;
                    }
                    else
                    {
                        dns = new string[1];
                        dns[0] = DNS.Text;
                    }
                }
                else
                {
                    dns = null;
                }

                if(SetIPAddress(adapter, ip, submask, gateway, dns))
                {
                    MessageBox.Show("Set successfully!");
                }
                else
                {
                    MessageBox.Show("Setting failed!");
                };
            }
        }
    }
}

3.7 UI code (xaml)

<Window x:Class="nextseq_utils.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:nextseq_utils"
        mc:Ignorable="d"
        Title="MainWindow" Height="625" Width="500">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ComboBox x:Name="AdapterSelector" HorizontalAlignment="Left" Height="30" Margin="192,43,0,0" VerticalAlignment="Top" Width="239" FontSize="14" SelectionChanged="ComboBox_SelectionChanged"/>
        <Label HorizontalContentAlignment="Center" Content="network card" HorizontalAlignment="Left" Height="30" VerticalAlignment="Top" Width="119" Margin="52,43,0,0" FontSize="14"/>
        <Label HorizontalContentAlignment="Center" Content="obtain IP mode" HorizontalAlignment="Left" Height="30" VerticalAlignment="Top" Width="119" Margin="52,93,0,0" FontSize="14"/>
        <ComboBox x:Name="IsAutoSelector" HorizontalAlignment="Left" Height="30" Margin="192,93,0,0" VerticalAlignment="Top" Width="239" FontSize="14" SelectionChanged="ComboBox_SelectionChanged_1">
            <ComboBoxItem Content="automatic"/>
            <ComboBoxItem Content="Manual"/>
        </ComboBox>
        <Label HorizontalContentAlignment="Center" Content="IP address" HorizontalAlignment="Left" Height="30" VerticalAlignment="Top" Width="119" Margin="52,143,0,0" FontSize="14"/>
        <TextBox x:Name="IpAddress" IsEnabled="False" VerticalContentAlignment="Center" HorizontalAlignment="Left" Height="30" Margin="192,143,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="239" FontSize="14"/>
        <Label HorizontalContentAlignment="Center" Content="Subnet mask" HorizontalAlignment="Left" Height="30" VerticalAlignment="Top" Width="119" Margin="52,193,0,0" FontSize="14"/>
        <TextBox x:Name="subnetMask" IsEnabled="False" VerticalContentAlignment="Center" HorizontalAlignment="Left" Height="30" Margin="192,193,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="239" FontSize="14"/>
        <Label HorizontalContentAlignment="Center" Content="gateway" HorizontalAlignment="Left" Height="30" VerticalAlignment="Top" Width="119" Margin="52,243,0,0" FontSize="14"/>
        <TextBox x:Name="Gateway" IsEnabled="False" VerticalContentAlignment="Center" HorizontalAlignment="Left" Height="30" Margin="192,243,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="239" FontSize="14"/>
        <Label HorizontalContentAlignment="Center" Content="main DNS" HorizontalAlignment="Left" Height="30" VerticalAlignment="Top" Width="119" Margin="52,294,0,0" FontSize="14"/>
        <TextBox x:Name="DNS" IsEnabled="False" VerticalContentAlignment="Center" HorizontalAlignment="Left" Height="30" Margin="192,294,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="239" FontSize="14"/>
        <Label HorizontalContentAlignment="Center" Content="spare DNS" HorizontalAlignment="Left" Height="30" VerticalAlignment="Top" Width="119" Margin="52,343,0,0" FontSize="14"/>
        <TextBox x:Name="DNS2" IsEnabled="False" VerticalContentAlignment="Center" HorizontalAlignment="Left" Height="30" Margin="192,343,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="239" FontSize="14"/>
        <Label HorizontalContentAlignment="Center" Content="DHCP The server" HorizontalAlignment="Left" Height="30" VerticalAlignment="Top" Width="119" Margin="52,393,0,0" FontSize="14"/>
        <TextBox x:Name="DHCPServer" IsEnabled="False"  VerticalContentAlignment="Center" HorizontalAlignment="Left" Height="30" Margin="192,393,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="239" FontSize="14"/>
        <Label HorizontalContentAlignment="Center" Content="Physical address" HorizontalAlignment="Left" Height="30" VerticalAlignment="Top" Width="119" Margin="52,443,0,0" FontSize="14"/>
        <TextBox x:Name="MAC" IsEnabled="False" VerticalContentAlignment="Center" HorizontalAlignment="Left" Height="30" Margin="192,443,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="239" FontSize="14"/>
        <Button x:Name="SettingIP" Content="set up IP" IsEnabled="False"  HorizontalAlignment="Left" Height="30" Margin="80,502,0,0" VerticalAlignment="Top" Width="100" FontSize="14" Click="Button_Click_2"/>
        <Button Content="Enable connection" HorizontalAlignment="Left" Height="30" Margin="206,502,0,0" VerticalAlignment="Top" Width="100" FontSize="14" Click="Button_Click" />
        <Button Content="Disable connection" HorizontalAlignment="Left" Height="30" Margin="330,502,0,0" VerticalAlignment="Top" Width="100" FontSize="14" Click="Button_Click_1" />
    </Grid>
</Window>

4 problems encountered in development

4.1 operation environment problems

This tool is mainly provided for illumina's sequencer. Some sequencer models of the company are relatively old, the operating system is windows 7, and under the condition of stable operation, it is basically not allowed to upgrade the operating system or Net framework, so the running environment of the program must be degraded to Net 4.0.
Note: codes can be used with Net 4.0 and Net 6.0 is fully compatible and can be compiled and run without any change! Compatibility has to praise Microsoft!
Solution:
① Install Visual Studio build tool 2019 and check it Net desktop generation tool and install the relevant SDK.

② Configure in Visual Studio 2022. The default checked WPF development environment is currently Net 6.0, we need to downgrade it.
Explorer → click item → right click → properties

After selection, Visual Studio 2022 will automatically perform relevant configuration. The process will not prompt if it is still in the process of subsequent release or operation Net 6.0 can try to clean up the project and restart Visual Studio to reset. If the operation ① is not performed, it may be prompted that the relevant running environment is not installed.

4.2 namespace 'Management' does not exist in 'System'

This problem has different solutions in different operating environments. And the solution is completely different.
① .Net 6.0
In this version of the running environment, system Management exists as a third-party library. Right click the dependency in Explorer, click Manage NuGet package, and search system Management, install the corresponding version of system Management.

② .Net 4.0
In this release, system Management exists as a built-in referential assembly. Right click dependency in Explorer, click add new reference, and check system. In the assembly drop-down list Click OK after management.

4.3 run with administrator privileges

The program needs to be run with administrator privileges, and the following methods are effective.
In resource management, right-click Properties → add → new item → application manifest file, add file and modify app The manifest is shown in the figure below.


4.4 others

See the comments in the code section for this section.

Keywords: C# Windows Visual Studio

Added by greekuser on Fri, 28 Jan 2022 13:05:39 +0200