C#, Obter hora de maquinas da rede

Segue abaixo uma elegante classe em C# para buscar a hora em micros da rede...


namespace GetHora
{
    public class NewHour
        
    {
        public DateTime GetNovaHora (string strMaquina)
        {
            IntPtr handle = IntPtr.Zero;
            DateTime dt;
            if (NetRemoteTOD("\\\\" + strMaquina, ref handle) == NERR_Success) 

            { 
                TIME_OF_DAY_INFO time = (TIME_OF_DAY_INFO) _
Marshal.PtrToStructure ( handle, typeof( TIME_OF_DAY_INFO ) );
                    
                dt = new DateTime ((int)time.tod_year, 
                                (int)time.tod_month, 
                                (int)time.tod_day, 
                                (int)(time.tod_hours - 
                                (time.tod_timezone / 60)), 
                                (int)time.tod_mins, 
                                (int)time.tod_secs);
                    

                uint result = NetApiBufferFree (handle);
                if (result != NERR_Success)
                Console.WriteLine ( "Memory cleanup failed: {0}",result );
                return dt;
            }

            return GetNovaHora("localhost");
            
        }

private const uint NERR_Success = 0;

[DllImport("netapi32.dll", SetLastError=false)]
private static extern uint NetApiBufferFree ( IntPtr Buffer );

[DllImport ( "netapi32.dll", CharSet = CharSet.Unicode,
SetLastError = false )]
private static extern uint NetRemoteTOD ( string
UncServerName, ref IntPtr BufferPtr );

[StructLayout(LayoutKind.Sequential)]
private struct TIME_OF_DAY_INFO
    {
        public uint tod_elapsedt;
        public uint tod_msecs;
        public uint tod_hours;
        public uint tod_mins;
        public uint tod_secs;
        public uint tod_hunds;
        public uint tod_timezone;
        public uint tod_tinterval;
        public uint tod_day;
        public uint tod_month;
        public uint tod_year;
        public uint tod_weekday;
    }
}
}

para usar instancie a classe e mande o valor para algum campo...
ex:

NewHour HoraServidor = new NewHour();
textBox1.Text = Convert.ToString(HoraServidor.GetNovaHora("faturamento"));

0 comentários:

Postar um comentário