Monday, 5 August 2013

Get current time on a remote system using C#

   You can get current date and time on a remote machine by using NET TIME command through command window. Here I have written the C# function to use NET TIME. It will be considered fastest method compared with getting date time by using WMI code.

Date Time on Remote system using NET TIME in C#

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace RemoteSystemTime
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string machineName = "vista-pc";
                Process proc = new Process();
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.FileName = "net";
                proc.StartInfo.Arguments = @"time \\" + machineName;
                proc.Start();
                proc.WaitForExit();

                List<string> results = new List<string>();

                while (!proc.StandardOutput.EndOfStream)
                {
                    string currentline = proc.StandardOutput.ReadLine();

                    if (!string.IsNullOrEmpty(currentline))
                    {
                        results.Add(currentline);
                    }
                }

                string currentTime = string.Empty;

                if (results.Count > 0 && results[0].ToLower().StartsWith(@"current time at \\" + machineName.ToLower() + " is "))
                {
                    currentTime = results[0].Substring((@"current time at \\" +
                                  machineName.ToLower() + " is ").Length);

                    Console.WriteLine(DateTime.Parse(currentTime));
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
    }
}


Related Articles:

Convert DateTime to Ticks and Ticks to DateTime in C#
Convert Object To Byte Array and Byte Array to Object in C#
Add or Remove programs using C# in Control Panel 
Show balloon tooltip c#
How to read data from csv file in c# 
Bulk Insert into SQL Server using SqlBulkCopy in C#
Import CSV File Into SQL Server Using SQL Bulk Copy

Thanks,
Morgan
Software Developer

Advertisements
Advertisements

No comments:

Post a Comment