如何使用C#修改本地Windows系统时间
作者:MarkYUN 发布时间:2022-05-06 08:23:00
标签:c#,系统时间,本地时间,windows时间
C#提升管理员权限修改本地Windows系统时间
在桌面应用程序开发过程中,需要对C盘下进行文件操作或者系统参数进行设置,例如在没有外网的情况下局域网内部自己的机制进行时间同步校准,这是没有管理员权限便无法进行设置。
1. 首先需要获得校准时间,两种方式:
通过可上网的电脑进行外部获取当前时间。
通过NTP实现
//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. 转换为本地时间
//传输时间戳字段偏移量,以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. 获取当前是否是管理员
public static bool IsAdministrator()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
4. 引入dll
[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 |
默认权限:
<requestedExecutionLevel level="asInvoker " uiAccess="false" />
asInvoker 表示当前用户本应该具有的权限
highestAvailable 表示提升当前用户最高权限
requireAdministrator 表示提升为管理员权限
修改权限:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
6. 重新生成程序
源码
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;
}
}
}
来源:https://www.cnblogs.com/MarkYUN/p/14282435.html
0
投稿
猜你喜欢
- 先看代码public class TestDemo1 { public static void main(String[] ar
- 这篇文章主要介绍了SpringBoot FreeWorker模板技术解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考
- 在你的jar文件当前目录中建立一个bat文件:内容是:注意文件名要对应@echo offSTART "commandServer&
- 前言在 Java 中,跳转的实现方式有两种:请求转发和请求重定向,但二者是完全不同的,所以我们今天就来盘它。请求转发和请求重定向主要区别,包
- 一、堆的创建1、向下调整(以小堆为例) 让parent标记需要调整的节点,child标记parent的左孩子(注意:parent
- start方法和run方法$start()$方法用来启动一个线程,这时此线程处于就绪(可运行)状态,并没有运行,一旦得到$cpu$时间片,就
- 很久以来都想研究一下利用java操作Excel的方法,今天没事,就稍微了解了一下,特总结一下。利用java操作Excel,有个开源的东东-j
- 前言:sleep 方法和 wait 方法都是用来将线程进入休眠状态的,并且 sleep 和 wait 方法都可以响应 interrupt 中
- Java去掉指定字符串的开头的指定字符/** * 去掉指定字符串的开头的指定字符 *
- 今天在做项目的时候突然遇到一个问题:启动服务器的时候spring没报错,可是当我访问某个页面的时候spring报Request bean i
- 实验环境hadoop版本:3.3.2jdk版本:1.8hadoop安装系统:ubuntu18.04编程环境:IDEA编程主机:windows
- 传统的多分支方式(圈复杂度为6):public String order(String type) { if ("1&
- 今天被数据大神说了,对接第三方接口返回的json字段我想用驼峰形式,他说我这样不专业。所以就改了,认怂。记住以后再次对接rest接口,返回的
- 昨天下午快下班的时候,无意中听到公司两位同事在探讨批量向数据库插入数据的性能优化问题,顿时来了兴趣,把自己的想法向两位同事说了一下,于是有了
- 前言在上网的时候我们常常遇到文件上传的情况,例如上传头像、上传资料等;当然除了上传,遇见下载的情况也很多,接下来看看我们 servlet 中
- 为了实现不同环境构建的不同需求,这里使用到了 profile。因为 profile 能够在构建时修改 pom 的一个子集,或者添加额外的配置
- Java 15 在 2020 年 9 月发布,虽然不是长久支持版本,但是也带来了 14 个新功能,这些新功能中有不少是十分实用的。Java
- 谷歌官方推出了一种侧滑菜单的实现方式(抽屉效果),即 DrawerLayout,这个类是在Support Library里的,需要加上and
- 动态数据源在很多具体应用场景的时候,我们需要用到动态数据源的情况,比如多租户的场景,系统登录时需要根据用户信息切换到用户对应的数据库。又比如
- 近来复习数据结构,自己动手实现了栈。栈是一种限制插入和删除只能在一个位置上的表。最基本的操作是进栈和出栈,因此,又被叫作“先进后出”表。首先