另一台机器的时间
本文关键字:机器 时间 一台 | 更新日期: 2023-09-27 17:59:02
在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();
}
}
}
}