Set System Time Zone from .NET

前端 未结 2 1454
再見小時候
再見小時候 2020-11-28 13:24

Does anyone have some code that will take a TimeZoneInfo field from .NET and execute the interop code to set the system time zone via SetTimeZoneInformation? I realize that

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 14:04

    There's another way to do this, which admittedly is a bit of a hack, but works quite well in practice:

    public void SetSystemTimeZone(string timeZoneId)
    {
        var process = Process.Start(new ProcessStartInfo
        {
            FileName = "tzutil.exe",
            Arguments = "/s \"" + timeZoneId + "\"",
            UseShellExecute = false,
            CreateNoWindow = true
        });
    
        if (process != null)
        {
            process.WaitForExit();
            TimeZoneInfo.ClearCachedData();
        }
    }
    

    Simply call this method and pass the TimeZoneInfo.Id that you wish to set. For example:

    SetSystemTimeZone("Eastern Standard Time");
    

    No special privileges are required to run this code, as tzutil.exe already has the appropriate permissions.

提交回复
热议问题