Enumerare porte di sistema

Esempio di come enumerare le porte di sistema.

namespace EnumPorts

{

public class PortHelper

{

[Flags]

public enum PortType:int

{

write =0x1,

read =0x2,

redirected = 0x4,

net_attached=0x8

}

[StructLayout(LayoutKind.Sequential)]

public struct PORT_INFO_2

{

public string pPortName;

public string pMonitorName;

public string pDescription;

public PortType fPortType;

internal int Reserved;

}

[DllImport("winspool.drv", EntryPoint="EnumPortsA",SetLastError=true)]

private static extern int EnumPorts (string pName, int Level, IntPtr lpbPorts, int cbBuf,ref int pcbNeeded,ref int pcReturned);

public static PORT_INFO_2[] GetAvailablePorts()

{

return GetAvailablePorts("");

}

public static PORT_INFO_2[] GetAvailablePorts(string servername)

{

int ret;

int pcbNeeded=0; int pcReturned=0; int lastErr =0; IntPtr TempBuff=IntPtr.Zero;

PORT_INFO_2[] pinfo=null;

ret=EnumPorts(servername,2,TempBuff,0,ref pcbNeeded,ref pcReturned);

try

{

TempBuff=Marshal.AllocHGlobal(pcbNeeded+1);

ret = EnumPorts(servername, 2, TempBuff, pcbNeeded,ref pcbNeeded,ref pcReturned);

lastErr=Marshal.GetLastWin32Error();

if (ret!=0)

{

IntPtr CurrentPort =TempBuff;

pinfo=new PORT_INFO_2[pcReturned];

for (int i=0;i<pcReturned;i++)

{

pinfo[i]=(PORT_INFO_2)Marshal.PtrToStructure(CurrentPort,typeof(PORT_INFO_2));

CurrentPort=(IntPtr)(CurrentPort.ToInt32()+Marshal.SizeOf(typeof(PORT_INFO_2)));

}

CurrentPort=IntPtr.Zero;

}

return pinfo;

}

finally

{

if (TempBuff!=IntPtr.Zero)

{

Marshal.FreeHGlobal(TempBuff);

TempBuff=IntPtr.Zero;

}

}

}

}

}

Print | posted on martedì 14 giugno 2005 22:49