public List <String> GetInstalledPorts() { //Alternative: prnport.vbs, uint pcbNeeded = 0; uint pcReturned = 0; if (EnumPorts(null, 2, IntPtr.Zero, 0, ref pcbNeeded, ref pcReturned)) { //succeeds, but must not, because buffer is zero (too small)! throw new Exception("EnumPorts should fail!"); } int lastWin32Error = Marshal.GetLastWin32Error(); //ERROR_INSUFFICIENT_BUFFER = 122 expected, if not -> Exception if (lastWin32Error != 122) { throw new Win32Exception(lastWin32Error); } IntPtr pPorts = Marshal.AllocHGlobal((int)pcbNeeded); if (EnumPorts(null, 2, pPorts, pcbNeeded, ref pcbNeeded, ref pcReturned)) { IntPtr currentPort = pPorts; PORT_INFO_2[] 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))); } Marshal.FreeHGlobal(pPorts); List <String> result = new List <string>(); for (int i = 0; i < pcReturned; i++) { result.Add(pinfo[i].pPortName); } return(result); } throw new Win32Exception(Marshal.GetLastWin32Error()); }
/// <summary> /// Lista as portas disponíveis no computador, "server" recebe uma string vazia para o /// servidor local ou nome do servidor remoto /// </summary> private static PORT_INFO_2[] GetAvailablePorts(String server) { int ret; int pcbNeeded = 0; int pcReturned = 0; int lastErr = 0; IntPtr TempBuff = IntPtr.Zero; PORT_INFO_2[] pinfo = null; ret = EnumPorts(server, 2, TempBuff, 0, ref pcbNeeded, ref pcReturned); try { TempBuff = Marshal.AllocHGlobal(pcbNeeded + 1); ret = EnumPorts(server, 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; } } }