Introduction
NetCfgTest uses the DDK interface INetCfg
and related interfaces to fetch a network adapter list (installed on the system). This article describes:
- How to write interop code for pure COM interfaces.
- How to use
INetCfg
in C# to fetch installed network adapters.
- How to initialize a pure COM class from C#.
Background
There was a requirement to use the interface INetCfg
in C#. I struggled to get a COM interop for this interface. Finally, I decided to write one.
Using the Code
The interface INetCfg
is written in the namespace NetCfg
. We can use the following source code to fetch an adapters list.:
object objINetCfg = null;
int nRet = 0;
nRet = Ole32Methods.CoCreateInstance(ref INetCfg_Guid.CLSID_CNetCfg, null,
Ole32Methods.CLSCTX_INPROC_SERVER, ref INetCfg_Guid.IID_INetCfg, out objINetCfg);
INetCfg netCfg = objINetCfg as INetCfg;
nRet = netCfg.Initialize(IntPtr.Zero);
object componet = new object();
nRet = netCfg.QueryNetCfgClass(ref INetCfg_Guid.IID_DevClassNet,
ref INetCfg_Guid.IID_INetCfgClass, out componet);
INetCfgClass NetCfgClass = componet as INetCfgClass;
object EnumNetCfgComponentObj = new object();
nRet = NetCfgClass.EnumComponents(out EnumNetCfgComponentObj);
IEnumNetCfgComponent EnumNetCfgComponent =
EnumNetCfgComponentObj as IEnumNetCfgComponent;
EnumNetCfgComponent.Reset();
object netCfgCompObj = new object();
INetCfgComponent netcfgcomp = null;
int outCelt = 0;
nRet = EnumNetCfgComponent.Next(1, out netCfgCompObj, out outCelt);
netcfgcomp = netCfgCompObj as INetCfgComponent;
string strBind;
string strDispName = "";
do
{
netcfgcomp.GetBindName(out strBind);
netcfgcomp.GetDisplayName(out strDispName);
System.Runtime.InteropServices.Marshal.ReleaseComObject(netcfgcomp);
netCfgCompObj = null;
this.listBox1.Items.Add(strDispName+" - " + strBind);
nRet = EnumNetCfgComponent.Next(1, out netCfgCompObj, out outCelt);
netcfgcomp = netCfgCompObj as INetCfgComponent;
GC.Collect();
} while (nRet == 0);
System.Runtime.InteropServices.Marshal.ReleaseComObject(EnumNetCfgComponent);
EnumNetCfgComponent = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(objINetCfg);
objINetCfg = null;
GC.Collect();
Points of Interest
I wrote interop for a pure COM interface for the first time. It was really interesting to learn the nitty-gritty of how to use a pure COM interface in C#.
History
- Sep. 26, 2008: Created version 1.0.