最近遇到个项目,需要控制软件使用时间,由于电脑不联网可以修改时间,故需要联网使电脑同步网络时间

网上寻找了很多解决方案,代码如下:

//Forproc_Win32.cs
//对常用Win32 API函数及结构的声明
using System;
using System.Runtime.InteropServices;
 
namespace Farproc.Win32
{
    /// <summary>
    ///
    /// </summary>
    public struct SYSTEMTIME
    {
        public ushort wYear;
        public ushort wMonth;
        public ushort wDayOfWeek;
        public ushort wDay;
        public ushort wHour;
        public ushort wMinute;
        public ushort wSecond;
        public ushort wMilliseconds;
 
        /// <summary>
        /// 从System.DateTime转换。
        /// </summary>
        /// <param name="time">System.DateTime类型的时间。</param>
        public void FromDateTime(DateTime time)
        {
            wYear = (ushort)time.Year;
            wMonth = (ushort)time.Month;
            wDayOfWeek = (ushort)time.DayOfWeek;
            wDay = (ushort)time.Day;
            wHour = (ushort)time.Hour;
            wMinute = (ushort)time.Minute;
            wSecond = (ushort)time.Second;
            wMilliseconds = (ushort)time.Millisecond;
        }
        /// <summary>
        /// 转换为System.DateTime类型。
        /// </summary>
        /// <returns></returns>
        public DateTime ToDateTime()
        {
            return new DateTime(wYear, wMonth, wDay, wHour, wMinute, wSecond, wMilliseconds);
        }
        /// <summary>
        /// 静态方法。转换为System.DateTime类型。
        /// </summary>
        /// <param name="time">SYSTEMTIME类型的时间。</param>
        /// <returns></returns>
        public static DateTime ToDateTime(SYSTEMTIME time)
        {
            return time.ToDateTime();
        }
    }
 public class Win32API
    {
        [DllImport("Kernel32.dll")]
        public static extern bool SetLocalTime( ref SYSTEMTIME Time );
        [DllImport("Kernel32.dll")]
        public static extern void GetLocalTime(ref SYSTEMTIME Time);
    }
}
private void button1_Click(object sender, System.EventArgs e)
{
    //取得当前系统时间
    DateTime t = DateTime.Now;
    //在当前时间上加上一周
    t = t.AddDays(7);
    //转换System.DateTime到SYSTEMTIME
    SYSTEMTIME st = new SYSTEMTIME();
    st.FromDateTime(t);
    //调用Win32 API设置系统时间
    Win32API.SetLocalTime(ref st);
    //显示当前时间
    MessageBox.Show(DateTime.Now.ToString());
}

试过很多次,都没能正确修改。

后来突发奇想,cmd不是能修改系统时间吗?

然后用cmd命令成功实现了功能。

/// <summary>  
        /// 获取网络日期时间  
        /// </summary>  
        /// <returns></returns>  
        public static string GetNetDateTime()
        {
            WebRequest request = null;
            WebResponse response = null;
            WebHeaderCollection headerCollection = null;
            string datetime = string.Empty;
            try
            {
                request = WebRequest.Create("https://www.baidu.com");
                request.Timeout = 3000;
                request.Credentials = CredentialCache.DefaultCredentials;
                response = (WebResponse)request.GetResponse();
                headerCollection = response.Headers;
                foreach (var h in headerCollection.AllKeys)
                { if (h == "Date") { datetime = headerCollection[h]; } }
                return datetime;
            }
            catch (Exception) { return datetime; }
            finally
            {
                if (request != null)
                { request.Abort(); }
                if (response != null)
                { response.Close(); }
                if (headerCollection != null)
                { headerCollection.Clear(); }
            }
        }

//调用cmd修改系统时间
        public static void setSystemTime(DateTime netTime)
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
            p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
            p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
            p.StartInfo.CreateNoWindow = true;//不显示程序窗口
            p.Start();//启动程序

string dtdate = netTime.ToString("yyyy-MM-dd");//获取日期
            string dttime = netTime.ToString("HH:mm:ss");//获取时间
            string dos1 = "date " + dtdate;//命令1
            string dos2 = "time " + dttime;//命令2
            p.StandardInput.WriteLine(dos1 + "&" + dos2 + "&exit");
            p.StandardInput.AutoFlush = true;
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();//等待程序执行完退出进程
            p.Close();
        }

c#将电脑时间同步到网络时间的更多相关文章

  1. SYN2102型 NTP网络时间服务器

    SYN2102型  NTP网络时间服务器   ntp主时钟服务器ntp时钟服务器厂商使用说明视频链接: http://www.syn029.com/h-pd-57-0_310_1_-1.html 请将 ...

  2. GPS校时器,GPS时钟装置,NTP网络时间服务器

    GPS校时器,GPS时钟装置,NTP网络时间服务器 GPS校时器,GPS时钟装置,NTP网络时间服务器 GPS校时器,GPS时钟装置,NTP网络时间服务器 GPS校时器,GPS时钟装置,NTP网络时间 ...

  3. 配置NTP网络时间自动校对系统时间和创建备份文件

    1 案例1:配置用户和组账号 1.1 问题 本例要求创建下列用户.组以及组的成员关系: 新建用户 alex,其用户ID为3456,密码是flectrag 创建一个名为 adminuser 的组 创建一 ...

  4. Linux服务器同步网络时间

    Linux服务器运行久时,系统时间就会存在一定的误差,一般情况下可以使用date命令进行时间设置,但在做数据库集群分片等操作时对多台机器的时间差是有要求的,此时就需要使用ntpdate进行时间同步. ...

  5. linux系统时间与网络时间不同步

    在解决问题之前,我们首先来了解下面几个知识点: 1. date命令: #date 显示系统时间 2.hwclock命令   (即hardwareclock系统硬件时间) #hwclock 显示硬件时间 ...

  6. SYN2136型 北斗NTP网络时间服务器

    SYN2136型  北斗NTP网络时间服务器 北斗NTP网络时间服务器时间服务器使用说明视频链接: http://www.syn029.com/h-pd-109-0_310_36_-1.html 请将 ...

  7. SYN2101型 NTP网络时间服务器

    SYN2101型  NTP网络时间服务器   时钟校准服务器时间 ntp服务器ntp时间校准服务器使用说明视频链接: http://www.syn029.com/h-pd-56-0_310_1_-1. ...

  8. 使用 NTP/Chrony 同时 Centos7 网络时间

    Network Time Protocol(NTP)是用来使计算机时间同步化的一种协议,它可以使计算机对其服务器或时钟源(如石英钟,GPS等等)做同步化,提供高精准度的时间校正服务. 在 Centos ...

  9. Linux实验:NTP网络时间服务器

    [实验目的]    1)掌握时间服务器的搭建方法    2)掌握客户机与时间服务同步时间的方法[实验原理]    NTP服务器[Network Time Protocol(NTP)]是用来使计算机时间 ...

随机推荐

  1. plus.zip.compressImage 压缩报错{"code":-5,"message":"输出图片失败"}

    var pathCompress = "_doc/" + getNowFormatDate(new Date()) + ' ' + Math.random() + ".c ...

  2. NMS(非极大值抑制)实现

    1.IOU计算 设两个边界框分别为A,B.A的坐标为Ax1,Ax2,Ay1,Ay2,且Ax1 < Ax2,Ay1 < Ay2.B和A类似. 则IOU为A∩B除以A∪B. 当两个边界框有重叠 ...

  3. Flutter移动电商实战 --(23)分类页_左侧类别导航制作

    自动生成dart类 https://javiercbk.github.io/json_to_dart/ 生成的代码 class Autogenerated { String code; String ...

  4. RGB-D(深度图像) & 图像深度

    RGB-D(深度图像)   深度图像 = 普通的RGB三通道彩色图像 + Depth Map   在3D计算机图形中,Depth Map(深度图)是包含与视点的场景对象的表面的距离有关的信息的图像或图 ...

  5. Linux下R环境安装

    R环境的两种安装方式,源码编译安装和yum在线安装 第一种:源码编译安装 1.首先,从官网上下载3.5.0版本 2.下载完后记得解压,我的习惯是解压在/usr/local下面 tar -zxvf R- ...

  6. SPSS python教程:[1]安装Python Essentials

    python机器学习-乳腺癌细胞挖掘(博主亲自录制视频)https://study.163.com/course/introduction.htm?courseId=1005269003&ut ...

  7. WinCE 开发问题:不支持 Open Generic 方法的 GetParameters。

    WinCE中用的是Newtonsoft.Json.Compact.dll序列化Json的, 今天用Json解析类的时候, 提示异常:不支持 Open Generic 方法的 GetParameters ...

  8. [转][C#]AutoFac 使用方法总结

    AutoFac使用方法总结:Part I 转自:http://niuyi.github.io/blog/2012/04/06/autofac-by-unit-test/ AutoFac是.net平台下 ...

  9. C# Socket TcpClient 无法从传输连接中读取数据: 远程主机强迫关闭了一个现有的连接。。

    开始的代码: byte[] data = Encoding.UTF8.GetBytes(sInfo);                    tcpns.Write(data, 0,1024); 修改 ...

  10. bs4笔记

    1.网页输出乱码的解决办法 r= requests.get('https://www.baidu.com/') r.encoding = 'gbk2312'   #有可能 gbk.utf-8 soup ...