获取远程电脑的日期时间?

发布于 2024-09-01 10:28:51 字数 103 浏览 7 评论 0原文

.net 中是否有任何类可用于获取远程 PC 的日期时间?为此,我可以使用计算机名称或时区。对于每种情况,是否有不同的方法来获取当前日期时间?我使用的是 Visual Studio 2005。

Is there any class available to get a remote PC's date time in .net? In order to do it, I can use a computer name or time zone. For each case, are there different ways to get the current date time? I am using Visual Studio 2005.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

吹泡泡o 2024-09-08 10:28:51

我为您提供了一个使用 WMI 的解决方案。您可能需要也可能不需要域和安全信息:

try
{
    string pc = "pcname";
    //string domain = "yourdomain";
    //ConnectionOptions connection = new ConnectionOptions();
    //connection.Username = some username;
    //connection.Password = somepassword;
    //connection.Authority = "ntlmdomain:" + domain;

    string wmipath = string.Format("\\\\{0}\\root\\CIMV2", pc);
    //ManagementScope scope = new ManagementScope(
    //    string.Format("\\\\{0}\\root\\CIMV2", pc), connection);
    ManagementScope scope = new ManagementScope(wmipath);
    scope.Connect();

    ObjectQuery query = new ObjectQuery(
        "SELECT * FROM Win32_LocalTime");

    ManagementObjectSearcher searcher =
        new ManagementObjectSearcher(scope, query);

    foreach (ManagementObject queryObj in searcher.Get())
    {
        Console.WriteLine("-----------------------------------");
        Console.WriteLine("Win32_LocalTime instance");
        Console.WriteLine("-----------------------------------");

        Console.WriteLine("Date: {0}-{1}-{2}", queryObj["Year"], queryObj["Month"], queryObj["Day"]);
        Console.WriteLine("Time: {0}:{1}:{2}", queryObj["Hour"], queryObj["Minute"], queryObj["Second"]);
    }
}
catch (ManagementException err)
{
    Console.WriteLine("An error occurred while querying for WMI data: " + err.Message);
}
catch (System.UnauthorizedAccessException unauthorizedErr)
{
    Console.WriteLine("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message);
}

I give you a solution which uses WMI. You may or may not need the domain and security information:

try
{
    string pc = "pcname";
    //string domain = "yourdomain";
    //ConnectionOptions connection = new ConnectionOptions();
    //connection.Username = some username;
    //connection.Password = somepassword;
    //connection.Authority = "ntlmdomain:" + domain;

    string wmipath = string.Format("\\\\{0}\\root\\CIMV2", pc);
    //ManagementScope scope = new ManagementScope(
    //    string.Format("\\\\{0}\\root\\CIMV2", pc), connection);
    ManagementScope scope = new ManagementScope(wmipath);
    scope.Connect();

    ObjectQuery query = new ObjectQuery(
        "SELECT * FROM Win32_LocalTime");

    ManagementObjectSearcher searcher =
        new ManagementObjectSearcher(scope, query);

    foreach (ManagementObject queryObj in searcher.Get())
    {
        Console.WriteLine("-----------------------------------");
        Console.WriteLine("Win32_LocalTime instance");
        Console.WriteLine("-----------------------------------");

        Console.WriteLine("Date: {0}-{1}-{2}", queryObj["Year"], queryObj["Month"], queryObj["Day"]);
        Console.WriteLine("Time: {0}:{1}:{2}", queryObj["Hour"], queryObj["Minute"], queryObj["Second"]);
    }
}
catch (ManagementException err)
{
    Console.WriteLine("An error occurred while querying for WMI data: " + err.Message);
}
catch (System.UnauthorizedAccessException unauthorizedErr)
{
    Console.WriteLine("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message);
}
浪漫之都 2024-09-08 10:28:51

由于 WMI 代码会非常慢,您可以使用下面的代码来获得更快的结果

            string machineName = "vista-pc";

            System.Diagnostics.Process proc = new System.Diagnostics.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();
            }

Since WMI code would be very slow, you can use the below code to get faster results

            string machineName = "vista-pc";

            System.Diagnostics.Process proc = new System.Diagnostics.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();
            }
蓝眼睛不忧郁 2024-09-08 10:28:51

在 Windows 计算机上,可以使用 net time \\ 来获取远程计算机的时间。您可以使用它来查找远程系统时间,如果您想要代码,您可以将其包装在函数中以在 C# 中执行 shell (DOS) 函数。

On a Windows machine there is net time \\<remote-ip address> to get the time of a remote machine. You could use that to find the remote system time, if you want code you can wrap it up in the function to execute the shell (DOS) functions in C#.

凉城凉梦凉人心 2024-09-08 10:28:51

您可以使用远程 WMI 和 Win32_TimeZone< /代码>类。您确实需要拥有在该计算机上执行 WMI 查询的权限。通过使用 UTC 而不是当地时间来避免这样的麻烦。

You can use remote WMI and the Win32_TimeZone class. You do need to have permission to execute WMI queries on that machine. Avoid hassle like this by working with UTC instead of local time.

心安伴我暖 2024-09-08 10:28:51

您可以使用 pinvoke NetRemoteTOD原生API。这是一个小型 PoC。

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]
struct TIME_OF_DAY_INFO
{
    public uint elapsedt;
    public int msecs;
    public int hours;
    public int mins;
    public int secs;
    public int hunds;
    public int timezone;
    public int tinterval;
    public int day;
    public int month;
    public int year;
    public int weekday;
}

class Program
{
    [DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
    private static extern int NetRemoteTOD(string uncServerName, out IntPtr buffer);

    [DllImport("netapi32.dll")] 
    private static extern void NetApiBufferFree(IntPtr buffer);

    internal static DateTimeOffset GetServerTime(string serverName = null)
    {
        if (serverName != null && !serverName.StartsWith(@"\\"))
        {
            serverName = @"\\" + serverName;
        }

        int rc = NetRemoteTOD(serverName, out IntPtr buffer);
        if (rc != 0)
        {
            throw new Win32Exception(rc);
        }

        try
        {
            var tod = Marshal.PtrToStructure<TIME_OF_DAY_INFO>(buffer);
            return DateTimeOffset.FromUnixTimeSeconds(tod.elapsedt).ToOffset(TimeSpan.FromMinutes(-tod.timezone));
        }
        finally
        {
            NetApiBufferFree(buffer);
        }
    }

    static void Main(string[] args)
    {
        Console.WriteLine(DateTimeOffset.Now);
        Console.WriteLine(GetServerTime());
        Console.WriteLine(GetServerTime("host1"));
        Console.WriteLine(GetServerTime("host2.domain.tld"));
        Console.ReadLine();
    }
}

You can use pinvoke to NetRemoteTOD native API. Here is a small PoC.

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]
struct TIME_OF_DAY_INFO
{
    public uint elapsedt;
    public int msecs;
    public int hours;
    public int mins;
    public int secs;
    public int hunds;
    public int timezone;
    public int tinterval;
    public int day;
    public int month;
    public int year;
    public int weekday;
}

class Program
{
    [DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
    private static extern int NetRemoteTOD(string uncServerName, out IntPtr buffer);

    [DllImport("netapi32.dll")] 
    private static extern void NetApiBufferFree(IntPtr buffer);

    internal static DateTimeOffset GetServerTime(string serverName = null)
    {
        if (serverName != null && !serverName.StartsWith(@"\\"))
        {
            serverName = @"\\" + serverName;
        }

        int rc = NetRemoteTOD(serverName, out IntPtr buffer);
        if (rc != 0)
        {
            throw new Win32Exception(rc);
        }

        try
        {
            var tod = Marshal.PtrToStructure<TIME_OF_DAY_INFO>(buffer);
            return DateTimeOffset.FromUnixTimeSeconds(tod.elapsedt).ToOffset(TimeSpan.FromMinutes(-tod.timezone));
        }
        finally
        {
            NetApiBufferFree(buffer);
        }
    }

    static void Main(string[] args)
    {
        Console.WriteLine(DateTimeOffset.Now);
        Console.WriteLine(GetServerTime());
        Console.WriteLine(GetServerTime("host1"));
        Console.WriteLine(GetServerTime("host2.domain.tld"));
        Console.ReadLine();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文