windows 使用 .NET 代码将系统时间同步到域控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1472225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:11:41  来源:igfitidea点击:

Sync system time to domain controller using .NET code

c#.netwindowsinterop

提问by helios456

I have time based tests to run that require changing the system time multiple times during the test. I want to be able to resync the time to the domain controller time at the end of the test. I there any way to do that using .NET code (C#). I am changing the time using the p-invoke function found in:

我要运行基于时间的测试,需要在测试期间多次更改系统时间。我希望能够在测试结束时将时间重新同步到域控制器时间。我有任何方法可以使用 .NET 代码 (C#) 做到这一点。我正在使用 p-invoke 函数更改时间:

Set time programmatically using C#

使用 C# 以编程方式设置时间

Thanks

谢谢

回答by Justin Grant

One easy way would be to launch a process and run the NET TIME command (copied from http://blogs.msdn.com/sanket/archive/2006/11/02/synchronizing-machine-time-with-domain-controller.aspx)

一种简单的方法是启动一个进程并运行 NET TIME 命令(从http://blogs.msdn.com/sanket/archive/2006/11/02/synchronizing-machine-time-with-domain-controller. aspx)

using System;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        Process netTime = new Process();

        netTime.StartInfo.FileName   = "NET.exe";
        netTime.StartInfo.Arguments = "TIME /domain:mydomainname /SET /Y";
        netTime.Start();
    }
}

回答by sleske

As an addition to the other answers:

作为其他答案的补充:

You should seriously consider making the notion of "current time" somehow injectable into your system. Directly reading from the system clock is very problematic (even when running the app), precisely because it is global state.

您应该认真考虑将“当前时间”的概念以某种方式注入您的系统。直接从系统时钟读取是非常有问题的(即使在运行应用程序时),正是因为它是全局状态。

回答by PVitt

You can do this using the command line tool w32tm:

您可以使用命令行工具 w32tm 执行此操作:

w32tm /resync 

This is neither C# nor .NET, but it hopefully fits your requirements.

这既不是 C# 也不是 .NET,但它希望符合您的要求。

回答by ParmesanCodice

The easiest way would be to use System.Diagnostics.Processto run a net timecommand with the appropriate parameters to sync back to your DC.

最简单的方法是使用System.Diagnostics.Process运行带有适当参数的net time命令以同步回您的 DC。

Run this from a command prompt to see what I'm talking about:

从命令提示符运行它以查看我在说什么:

net time /?