Home > Software engineering >  Network Interfaces list, abstract type or interface
Network Interfaces list, abstract type or interface

Time:01-01

I have program which list HDD drives and Network interfaces like in this picture: Network interfaces list

If I click on HDD name I can see drive type in text box. This is working fine. However if I try this code on network interface its not working. It gave error CS0144: Cannot create an instance of the abstract type or interface 'NetworkInterface'

Here is code:

 private void button2_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            textBox1.Text = "";
            DriveInfo[] Drives = DriveInfo.GetDrives();
            foreach (DriveInfo drv in Drives)
            {
                listBox1.Items.Add(drv.Name);
            }
        }
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            String strDrive = (string)listBox1.SelectedItem;
            DriveInfo drive = new DriveInfo(strDrive);

            textBox1.Text = drive.DriveType.ToString();
        }

And here is not working network interfaces:

private void button3_Click(object sender, EventArgs e)
        {
            listBox2.Items.Clear();
            textBox2.Text = "";
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in adapters)
            {
                listBox2.Items.Add(adapter.Name);
            }
        }

        private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            String strInterface = (string)listBox2.SelectedItem;
            NetworkInterface adapter = new NetworkInterface(strInterface);
            textBox2.Text = adapter.Description.ToString();
        }

This line is wrong: NetworkInterface adapter = new NetworkInterface(strInterface);

CodePudding user response:

From the NetworkInterface docs:

You do not create instances of this class; the GetAllNetworkInterfaces method returns an array that contains one instance of this class for each network interface on the local computer.

So you can call GetAllNetworkInterfaces again and filter the results:

var adapter = NetworkInterface.GetAllNetworkInterfaces()
    .FirstOrDefault(ni => ni.Name == strInterface);
// if not null ...

Or store results of previous call in some field/property and use those for search. Or just use the result array as datasource for listBox2 itself.

CodePudding user response:

You can store the NetworkInterface instances directly in the list box items:

listBox2.Items.Add(adapter);

And set listBox2.DisplayMember = nameof(NetworkInterface.Name) to make the list box display their names.

Then you can access the selected adapter as:

var adapter = (NetworkInterface)listBox2.SelectedItem;;
  • Related