问题描述
|
在c#中,当我们使用DateTime时,现在属性值是本地计算机的当前日期和时间
如何获得具有IP地址或机器名称的另一台机器的时间
解决方法
您可以通过编写提供当前时间的服务来实现目标吗?或连接到远程计算机并发送一些WMI查询
相似的问题:http://social.msdn.microsoft.com/forums/en-US/netfxremoting/thread/f2ff8a33-df5d-4bad-aa89-7b2a2dd73d73/
, 没有内置的方法可以做到这一点。您将不得不要求机器通过某种通讯协议告诉您其时间。例如,您可以创建WCF服务以在另一台计算机上运行,并公开服务合同以返回系统时间。请记住,由于网络跳变会导致一些延迟,因此您返回的时间将过时一些毫秒(或秒,具体取决于连接速度)。
如果您想要一种快速而又肮脏的方法来执行此操作,而该方法不需要.NET或在另一台计算机上运行任何特殊操作,则可以使用PSExec。
, 您可以在没有WMI的情况下通过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();
}
}
}
}