C#

  • 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; } } } } }

  • Data Random comprese da x a y

    using System; using System.Collections; public class MyClass { public static void Main() { RandomEx rg=new RandomEx(); DateTime di=new System.DateTime(2005,4,1); DateTime df=new System.DateTime(2005,5,1); for (int i=0;i<20;i++) { WL("Riga \t {0} \t {1}",i,rg.NextDateTime(di,df)); } RL(); } #region Helper methods private static void WL(object text, params object[] args) { Console.WriteLine(text.ToString(), args); } private static void RL() { Console.ReadLine(); } private static void Break() { System.Diagnostics.Debugger.Break(); } #endregion public class RandomEx:System.Random { public RandomEx():base() { } public RandomEx(int Seed):base(Seed) { } public virtual long Next(long minValue, long maxValue) { if (minValue > maxValue) { throw new ArgumentOutOfRangeException("minValue","Parametri non validi" ); } long num1 = maxValue - minValue; if (num1 < 0) { long num2 = maxValue - minValue; return (((long) ((long) (this.Sample() * num2))) + minValue); } return (((long) (this.Sample() * num1)) + minValue); }   public virtual System.DateTime NextDateTime() { return NextDateTime(new System.DateTime(1970,01,01),new System.DateTime(2050,12,31)); } public virtual System.DateTime NextDateTime(System.DateTime maxValue) { return NextDateTime(new System.DateTime(1970,01,01),maxValue); } public virtual...