服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - 如何使用C#修改本地Windows系统时间

如何使用C#修改本地Windows系统时间

2022-10-31 11:12MarkYUN C#

这篇文章主要介绍了如何使用C#修改本地Windows系统时间,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下

C#提升管理员权限修改本地Windows系统时间

​在桌面应用程序开发过程中,需要对C盘下进行文件操作或者系统参数进行设置,例如在没有外网的情况下局域网内部自己的机制进行时间同步校准,这是没有管理员权限便无法进行设置。

如何使用C#修改本地Windows系统时间

1. 首先需要获得校准时间,两种方式:

通过可上网的电脑进行外部获取当前时间。

通过NTP实现

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//NTP消息大小摘要是16字节 (RFC 2030)
byte[] ntpData = new byte[48];
//设置跳跃指示器、版本号和模式值
// LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)
ntpData[0] = 0x1B;
IPAddress ip = iPAddress;
// NTP服务给UDP分配的端口号是123
IPEndPoint ipEndPoint = new IPEndPoint(ip, 123);
// 使用UTP进行通讯
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(ipEndPoint);
socket.ReceiveTimeout = 3000;
socket.Send(ntpData);
socket.Receive(ntpData);
socket?.Close();
socket?.Dispose();

程序手动输入。

2. 转换为本地时间

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//传输时间戳字段偏移量,以64位时间戳格式,应答离开客户端服务器的时间
const byte serverReplyTime = 40;
// 获得秒的部分
ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
//获取秒的部分
ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
//由big-endian 到 little-endian的转换
intPart = swapEndian(intPart);
fractPart = swapEndian(fractPart);
ulong milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000UL);
// UTC时间
DateTime webTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds(milliseconds);
//本地时间
DateTime dt = webTime.ToLocalTime();

3. 获取当前是否是管理员

?
1
2
3
4
5
6
public static bool IsAdministrator()
    {
      WindowsIdentity identity = WindowsIdentity.GetCurrent();
      WindowsPrincipal principal = new WindowsPrincipal(identity);
      return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }

4. 引入dll

?
1
2
3
4
5
[DllImport("kernel32.dll")]
private static extern bool SetLocalTime(ref Systemtime time);
 
//转化后的时间进行本地设置,并返回成功与否
bool isSuccess = SetLocalDateTime(dt);

5. 提升权限

如果程序不是管理员身份运行则不可以设置时间

引入引用程序清单文件(app.manifest),步骤:添加新建项->选择‘应用程序清单文件(仅限windows)'

引入后再文件中出现app.manifest文件

 

Value Description Comment
asInvoker The application runs with the same access token as the parent process. Recommended for standard user applications. Do refractoring with internal elevation points, as per the guidance provided earlier in this document.
highestAvailable The application runs with the highest privileges the current user can obtain. Recommended for mixed-mode applications. Plan to refractor the application in a future release.
requireAdministrator The application runs only for administrators and requires that the application be launched with the full access token of an administrator. Recommended for administrator only applications. Internal elevation points

 

默认权限:

?
1
<requestedExecutionLevel level="asInvoker " uiAccess="false" />

asInvoker 表示当前用户本应该具有的权限

highestAvailable 表示提升当前用户最高权限

requireAdministrator 表示提升为管理员权限

修改权限:

?
1
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

6. 重新生成程序

源码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
 
namespace WindowsFormsApp1
{
 
  public class DateTimeSynchronization
  {
    [StructLayout(LayoutKind.Sequential)]
    private struct Systemtime
    {
      public short year;
      public short month;
      public short dayOfWeek;
      public short day;
      public short hour;
      public short minute;
      public short second;
      public short milliseconds;
    }
 
    [DllImport("kernel32.dll")]
    private static extern bool SetLocalTime(ref Systemtime time);
 
    private static uint swapEndian(ulong x)
    {
      return (uint)(((x & 0x000000ff) << 24) +
      ((x & 0x0000ff00) << 8) +
      ((x & 0x00ff0000) >> 8) +
      ((x & 0xff000000) >> 24));
    }
 
    /// <summary>
    /// 设置系统时间
    /// </summary>
    /// <param name="dt">需要设置的时间</param>
    /// <returns>返回系统时间设置状态,true为成功,false为失败</returns>
    private static bool SetLocalDateTime(DateTime dt)
    {
      Systemtime st;
      st.year = (short)dt.Year;
      st.month = (short)dt.Month;
      st.dayOfWeek = (short)dt.DayOfWeek;
      st.day = (short)dt.Day;
      st.hour = (short)dt.Hour;
      st.minute = (short)dt.Minute;
      st.second = (short)dt.Second;
      st.milliseconds = (short)dt.Millisecond;
      bool rt = SetLocalTime(ref st);
      return rt;
    }
    private static IPAddress iPAddress = null;
    public static bool Synchronization(string host, out DateTime syncDateTime, out string message)
    {
      syncDateTime = DateTime.Now;
      try
      {
        message = "";
        if (iPAddress == null)
        {
          var iphostinfo = Dns.GetHostEntry(host);
          var ntpServer = iphostinfo.AddressList[0];
          iPAddress = ntpServer;
        }
        DateTime dtStart = DateTime.Now;
        //NTP消息大小摘要是16字节 (RFC 2030)
        byte[] ntpData = new byte[48];
        //设置跳跃指示器、版本号和模式值
        // LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)
        ntpData[0] = 0x1B;
        IPAddress ip = iPAddress;
        // NTP服务给UDP分配的端口号是123
        IPEndPoint ipEndPoint = new IPEndPoint(ip, 123);
        // 使用UTP进行通讯
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        socket.Connect(ipEndPoint);
        socket.ReceiveTimeout = 3000;
        socket.Send(ntpData);
        socket.Receive(ntpData);
        socket?.Close();
        socket?.Dispose();
        DateTime dtEnd = DateTime.Now;
        //传输时间戳字段偏移量,以64位时间戳格式,应答离开客户端服务器的时间
        const byte serverReplyTime = 40;
        // 获得秒的部分
        ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
        //获取秒的部分
        ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
        //由big-endian 到 little-endian的转换
        intPart = swapEndian(intPart);
        fractPart = swapEndian(fractPart);
        ulong milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000UL);
        // UTC时间
        DateTime webTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds(milliseconds);
        //本地时间
        DateTime dt = webTime.ToLocalTime();
        bool isSuccess = SetLocalDateTime(dt);
        syncDateTime = dt;
 
      }
      catch (Exception ex)
      {
        message = ex.Message;
        return false;
      }
      return true;
 
    }
  }
}

以上就是如何使用C#修改本地Windows系统时间的详细内容,更多关于c#修改系统时间的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/MarkYUN/p/14282435.html

延伸 · 阅读

精彩推荐
  • C#WinForm调用百度地图接口用法示例

    WinForm调用百度地图接口用法示例

    这篇文章主要介绍了WinForm调用百度地图接口用法,结合具体实例形式简单分析了WinForm WebBrower控件与前端百度接口交互的相关操作技巧,需要的朋友可以参考...

    廖先生4952022-01-10
  • C#利用WCF双工模式实现即时通讯

    利用WCF双工模式实现即时通讯

    这篇文章主要介绍了利用WCF双工模式实现即时通讯的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    会长4152021-12-07
  • C#C#编程获取IP地址的方法示例

    C#编程获取IP地址的方法示例

    这篇文章主要介绍了C#编程获取IP地址的方法,结合实例形式分析了C#获取客户端IP地址的具体实现技巧,需要的朋友可以参考下...

    pan_junbiao3772021-12-21
  • C#C#的Excel导入、导出

    C#的Excel导入、导出

    这篇文章主要为大家详细介绍了C#的Excel导入、导出的相关资料,需要的朋友可以参考下...

    polk65252021-11-22
  • C#C#使用SQL DataReader访问数据的优点和实例

    C#使用SQL DataReader访问数据的优点和实例

    今天小编就为大家分享一篇关于C#使用SQL DataReader访问数据的优点和实例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起...

    Czhenya10382022-03-03
  • C#C#动态创建Access数据库及密码的方法

    C#动态创建Access数据库及密码的方法

    同为微软的产品,本文将讨论的是C#如何创建Access数据库,同时创建数据库密码与相关操作,希望对大家有所帮助。...

    C#教程网9362021-10-25
  • C#c#生成自定义图片方法代码实例

    c#生成自定义图片方法代码实例

    在本篇文章中我们给大家分享了关于c#生成自定义图片方法的相关内容,有需要的朋友们可以参考下。...

    C#教程网8582022-03-02
  • C#c#批量抓取免费代理并且验证有效性的实战教程

    c#批量抓取免费代理并且验证有效性的实战教程

    突破反爬虫限制的方法之一就是多用几个代理IP,下面这篇文章主要给大家介绍了关于利用c#批量抓取免费代理并且验证有效性的相关资料,文中通过示例代...

    张林-布莱恩特11412022-02-25