如何使用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;

    }
  }
}

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

(0)

相关推荐

  • C#利用win32 Api 修改本地系统时间、获取硬盘序列号

    C#利用win32 Api 修改本地系统时间.获取硬盘序列号,可以用于软件注册机制的编写! 复制代码 代码如下: using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace Fengyun {     public class Win32     {         #region 修改本地系统时间         [DllIm

  • C#实现修改系统时间的方法

    本文所述C#获取和修改系统时间的实现步骤为:系统的时间从 SystemTime 结构体中取出,并显示在textBox1上,从setDate,setTime控件中获取年,月,日,小时,分钟,秒信息,存入SystemTime结构体中,然后使用SetLocalTime(ref systemTime)设置为用户指定的时间.本代码编译后会有一个易于操作的窗体. 完整功能代码如下: using System; using System.Drawing; using System.Collections; u

  • C#/.NET读取或修改文件的创建时间及修改时间详解

    前言 手工在博客中添加 Front Matter 文件头可是个相当费事儿的做法,这种事情就应该自动完成. .NET 中提供了非常方便的修改文件创建时间的方法,使用这种方法,能够帮助自动完成一部分文件头的编写或者更新. 相关类型 .NET 中提供了两个不同的设置创建和修改时间的入口: File 静态类 FileInfo 类 ▲ File 静态类的方法 ▲ FileInfo 类的方法 很明显,使用 FileInfo 类可以使用属性直接获取和赋值,用法上会比 File 方便,不过需要一个 FileIn

  • 利用C#修改Windows操作系统时间

    C#的System.DateTime类提供了对日期时间的封装,用它进行时间的转换和处理很方便,但是我没有在其中找到任何可以用来修改系统时间的成员.用过VC.VB等的朋友可能知道,我们可以调用Win32 API SetLocalTime来改变系统时间,看来C#中也只能如此了.SetLocalTime需要一个SYSTEMTIME结构指针作为参数,这倒不难,我们可以"比葫芦画瓢"很快在C#中定义这个结构,但问题是,我同时还想"享受".NET Framework的Syste

  • C#简单读取、改变文件的创建、修改及访问时间的方法

    本文实例讲述了C#简单读取.改变文件的创建.修改及访问时间的方法.分享给大家供大家参考.具体如下: FileInfo fi = new FileInfo("C:\\test.txt"); Console.WriteLine(fi.CreationTime.ToString()); Console.WriteLine(fi.LastWriteTime.ToString()); Console.WriteLine(fi.LastAccessTime.ToString()); // 改变(设

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

    C#提升管理员权限修改本地Windows系统时间 ​在桌面应用程序开发过程中,需要对C盘下进行文件操作或者系统参数进行设置,例如在没有外网的情况下局域网内部自己的机制进行时间同步校准,这是没有管理员权限便无法进行设置. 1. 首先需要获得校准时间,两种方式: 通过可上网的电脑进行外部获取当前时间. 通过NTP实现 //NTP消息大小摘要是16字节 (RFC 2030) byte[] ntpData = new byte[48]; //设置跳跃指示器.版本号和模式值 // LI = 0 (no w

  • 用“组策略”阻止病毒修改系统时间的方法

    最近有些针对卡巴的病毒,通过修改Windows系统时间来使卡巴自动监控失效.针对这一病毒,通过简单的系统设置来阻止它使卡巴监控失效.方法如下 1.打开"控制面版" - "管理工具" - "本地安全设置" 然后依次选择本地策略--用户权利指派--更改系统时间 ]2.然后双击打开"更新系统时间配置"属性对话框,把里面所有权限用户名全部删除,然后点击确定,重启计算机 3.依次删除下图中的Administrators和Power Us

  • Windows系统下安装GIt及GIT基本认识和配置

    1. 安装 Git 在 Windows 系统中安装Git非常简单,只需要下载Git的安装包,然后安装引导点击安装即可: Git下载地址:https://git-scm.com/download/win 下载完安装包之后,双击 EXE 安装包,一直点击Next安装即可在安装完成之后,会在你的右键菜单栏中增加一个Git的选项,你可以在电脑桌面点击鼠标右键,会看到多出两个菜单,如下图所示: 当你点击Git bash Here菜单之后,可以看到一个终端窗口,在终端里面输入命令git --version,

  • CentOS7修改服务器系统时间的方法

    未知何故,服务器上的系统时间不对,比实际的UTC快了将近63分钟.在涉及本地文件与远程服务器文件的时间戳校验时,容易产生混淆. 这里把系统时间更正的过程记录如下. 参考资料:http://www.centoscn.com/CentOS/config/2015/0723/5901.html 在CentOS 7里面有一个命令timedatectl可以帮助我们修改服务器的时区. 1. 查看服务器里的时间设置 timedatectl ,它等同于 timedatectl status : $ timeda

  • Windows系统修改Jenkins端口号

    Jenkins默认使用的是8080端口进行访问,有时候需要根据自己的需求将默认的8080端口改掉,这篇文章将讲解如何更改Jenkins默认的8080端口. 在安装Jenkins的时候,会有一个配置Jenkins实例的界面,配置实例界面可以修改端口号,但是那里修改的端口号不起作用,需要修改配置文件里面的端口号. 一.关闭Jenkins服务 修改端口号之前要首先关掉Jenkins服务,Jenkins安装完成以后就会一直处于启动状态,除非手动将其关闭. 可以看到Jenkins是运行状态. 1.使用命令

  • 防止黑客侵入你正在使用的Windows系统(克隆管理员账户)

    防止黑客侵入你正在使用的Windows系统 当黑客入侵一台主机后,会想方设法保护自己的"劳动成果",因此会在肉鸡上留下种种后门来长时间得控制肉鸡,其中使用最多的就是账户隐藏技术.在肉鸡上建立一个隐藏的账户,以备需要的时候使用.账户隐藏技术可谓是最隐蔽的后门,一般用户很难发现系统中隐藏账户的存在,因此危害性很大,本文就对隐藏账户这种黑客常用的技术进行揭密. 在隐藏系统账户之前,我们有必要先来了解一下如何才能查看系统中已经存在的账户.在系统中可以进入"命令提示符",控制

  • 在Windows系统上安装Cygwin搭建Swoole测试环境的图文教程

    前言 昨天,在本地安装 Swoole 调试环境的时候,遇到好几个坑,因为我的电脑是 Windows 系统,所以安装的是 cygwin ,但是过程并不顺利,接连出现安装终端的问题,并一步步查资料排坑,最终也顺利安装成功了,为了让其他人也能一次性就安装成功,省掉很多麻烦闹心事,我特地写了这边文章,希望对有需要的人有所帮助. 下载Swoole Swoole下载地址: https://github.com/swoole/swoole-src/releases 在浏览器中打开下载地址,滑动到下载位置,可以

随机推荐