c#将电脑时间同步到网络时间
最近遇到个项目,需要控制软件使用时间,由于电脑不联网可以修改时间,故需要联网使电脑同步网络时间
网上寻找了很多解决方案,代码如下:
//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#将电脑时间同步到网络时间的更多相关文章
- SYN2102型 NTP网络时间服务器
SYN2102型 NTP网络时间服务器 ntp主时钟服务器ntp时钟服务器厂商使用说明视频链接: http://www.syn029.com/h-pd-57-0_310_1_-1.html 请将 ...
- GPS校时器,GPS时钟装置,NTP网络时间服务器
GPS校时器,GPS时钟装置,NTP网络时间服务器 GPS校时器,GPS时钟装置,NTP网络时间服务器 GPS校时器,GPS时钟装置,NTP网络时间服务器 GPS校时器,GPS时钟装置,NTP网络时间 ...
- 配置NTP网络时间自动校对系统时间和创建备份文件
1 案例1:配置用户和组账号 1.1 问题 本例要求创建下列用户.组以及组的成员关系: 新建用户 alex,其用户ID为3456,密码是flectrag 创建一个名为 adminuser 的组 创建一 ...
- Linux服务器同步网络时间
Linux服务器运行久时,系统时间就会存在一定的误差,一般情况下可以使用date命令进行时间设置,但在做数据库集群分片等操作时对多台机器的时间差是有要求的,此时就需要使用ntpdate进行时间同步. ...
- linux系统时间与网络时间不同步
在解决问题之前,我们首先来了解下面几个知识点: 1. date命令: #date 显示系统时间 2.hwclock命令 (即hardwareclock系统硬件时间) #hwclock 显示硬件时间 ...
- SYN2136型 北斗NTP网络时间服务器
SYN2136型 北斗NTP网络时间服务器 北斗NTP网络时间服务器时间服务器使用说明视频链接: http://www.syn029.com/h-pd-109-0_310_36_-1.html 请将 ...
- SYN2101型 NTP网络时间服务器
SYN2101型 NTP网络时间服务器 时钟校准服务器时间 ntp服务器ntp时间校准服务器使用说明视频链接: http://www.syn029.com/h-pd-56-0_310_1_-1. ...
- 使用 NTP/Chrony 同时 Centos7 网络时间
Network Time Protocol(NTP)是用来使计算机时间同步化的一种协议,它可以使计算机对其服务器或时钟源(如石英钟,GPS等等)做同步化,提供高精准度的时间校正服务. 在 Centos ...
- Linux实验:NTP网络时间服务器
[实验目的] 1)掌握时间服务器的搭建方法 2)掌握客户机与时间服务同步时间的方法[实验原理] NTP服务器[Network Time Protocol(NTP)]是用来使计算机时间 ...
随机推荐
- ubuntu 无法访问windows使用的磁盘
安装双系统的电脑,正常情况下Ubuntu是可以访问windows下使用的磁盘的, 当出现如下图所示问题时: Windows没有正常关闭. 解决方法: sudo apt-get install ntfs ...
- 数据库与linux中quota的作用
linux命令,quota 命令显示磁盘使用情况和限额.缺省情况下,或者带 -u 标志,只显示用户限额.quota 命令报告 /etc/filesystems 文件中列出的所有文件系统的限额.如果 q ...
- Java同步数据结构之PriorityBlockingQueue
前言 接下来继续BlockingQueue的另一个实现,优先级阻塞队列PriorityBlockingQueue.PriorityBlockingQueue是一个无限容量的阻塞队列,由于容量是无限的所 ...
- protobuf ubuntu 18.04环境下安装
(t20190518) luo@luo-All-Series:~/MyFile$ (t20190518) luo@luo-All-Series:~/MyFile$ (t20190518) luo@lu ...
- MySQL标准化、自动化部署
机器标准化:服务器的硬件配置(CPU.硬盘.内存.RAID)要保持一致 目录标准化: mysql的安装目录,存放数据的目录.日志文件等,多台机器上配置要统一 参数标准化: 多台服务器上,存放的my.c ...
- 阶段5 3.微服务项目【学成在线】_day04 页面静态化_09-freemarker基础-内建函数
可以理解为freemaker提供的一些函数和方法 controller里面记得把map的数据注释去掉,.放开代码 工程需要重启下 <br/> 学生的个数: ${stus?size} < ...
- 阶段5 3.微服务项目【学成在线】_day04 页面静态化_07-freemarker基础-if指令
<td <#if stu.name=="小明">style="background-color:cornflowerblue"</#if ...
- Python描述性统计numpy
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import datasets, ...
- SaaS领域如何分析收入增长?
SaaS领域如何分析收入增长? 今天我们试着将其模式运用到收入增长上进行分析.这对常规收入的计算会极有帮助,例如企业级应用软件(SaaS)或消费者订阅业务. 列举某公司通过月度订阅获得营收为例,为了更 ...
- python基础----redis模块
数据库 关系型数据 例如mysql,有表还有约束条件等 非关系型 k-v形式 memcache 存在内存中 redis 存在内存 mongodb 数据存在磁盘 import redis #string ...