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)]是用来使计算机时间 ...
随机推荐
- docker安装mysql挂载外部配置和数据目录
从docker hub上可以找到mysql外挂配置和数据目录的一些文档说明 https://hub.docker.com/_/mysql 从该文档中可以了解到,mysql的默认配置为/etc/mysq ...
- CentOS8安装Python3
安装CentOS8 如果使用vmware player安装CentOS8,会出现如下选项 其中Software Selection默认为带有GUI版本,即安装完成之后,带有图形界面,我本人不太喜欢使用 ...
- 使 nodejs 代码 在后端运行(forever)
情境 运行nodejs的程序,使用命令:node xxx.js,但是关掉终端,程序也关闭了,如何让node app的程序一直运行? 解决 1.安装forever npm install -g fore ...
- linux安装python3 大型的软件一定要安装在/ opt中 规范
关闭页面特效 linux中安装python 1.首先切换目录 大型的软件一定要安装在/ opt中 规范 cd /opt 2.下载python3的源码 wget https://www.p ...
- mysql密码设置为空怎么办?
由于很多童鞋安装使用MySQL时,安装时没有设置密码,或者像我一样图省事设置密码为空,想为其设置新密码: 1.点击 开始------>运行----在弹出的对话框中输入cmd 如下图: 2.使用 ...
- 图解centos7如何关闭ipv6仅使用ipv4
方法/步骤 使用ifconfig命令查看网卡信息,如果出现inet6 fe80::20c:29ff:fed0:3514,说明机器开启了ipv6,如下图所示: 编辑/etc/sysctl.c ...
- kafka----简单的脚本命令重点
kafka命令如下: kafka-shell基本命令 在节点hadoop-2,hadoop-3,hadoop-5,启动kafka 启动命令如下 kafka-server-start.sh /usr/l ...
- SpringMVC接收集合页面参数
SpringMVC接收集合页面参数 Spring MVC在接收集合请求参数时,需要在Controller方法的集合参数里前添加@RequestBody,而@RequestBody默认接收的enctyp ...
- 知识点整理-mysql的顺序I/O和随机I/O
假设有这样一张表: CREATE TABLE `person_info` ( `id` ) NOT NULL AUTO_INCREMENT, `name` varchar() NOT NULL, `b ...
- 19 个让 MySQL 效率提高 3 倍的 SQL 优化技巧
优化成本: 硬件>系统配置>数据库表结构>SQL及索引 优化效果: 硬件<系统配置<数据库表结构<SQL及索引 本文我们就来谈谈 MySQL 中常用的 SQL 优化 ...