Reputation: 7958
In c# when we use DateTime.Now the property value is current date & time of local machine how can get the time of another machine with IP address or machine's name
Upvotes: 3
Views: 4700
Reputation: 5496
You can get it by C# without WMI
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();
}
}
}
}
Upvotes: 0
Reputation: 24167
There is no built-in way to do this. You will have to ask the machine to tell you its time via some communication protocol. For example, you could create a WCF service to run on the other machine and expose a service contract to return the system time. Keep in mind there will be some latency due to the network hop, so the time you get back will be some number of milliseconds (or seconds depending on the connection speed) out of date.
If you want a quick and dirty way to do this which doesn't require .NET or anything special running on the other machine, you can use PSExec.
Upvotes: 0
Reputation: 1619
You can achive by writing a service that gives you the current time? or connecting to remote machine and sending some wmi query
Similar question: http://social.msdn.microsoft.com/forums/en-US/netfxremoting/thread/f2ff8a33-df5d-4bad-aa89-7b2a2dd73d73/
Upvotes: 3