using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Runtime; /// <summary>
/// 网络时间
/// </summary>
public class NetTime
{ /// <summary>
/// 获取标准北京时间,读取http://www.beijing-time.org/time.asp
/// </summary>
/// <returns>返回网络时间</returns>
public DateTime GetBeijingTime()
{ DateTime dt;
WebRequest wrt = null;
WebResponse wrp = null;
try
{
wrt = WebRequest.Create("http://www.beijing-time.org/time.asp");
wrp = wrt.GetResponse(); string html = string.Empty;
using (Stream stream = wrp.GetResponseStream())
{
using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
{
html = sr.ReadToEnd();
}
} string[] tempArray = html.Split(';');
for (int i = ; i < tempArray.Length; i++)
{
tempArray[i] = tempArray[i].Replace("\r\n", "");
} string year = tempArray[].Split('=')[];
string month = tempArray[].Split('=')[];
string day = tempArray[].Split('=')[];
string hour = tempArray[].Split('=')[];
string minite = tempArray[].Split('=')[];
string second = tempArray[].Split('=')[]; dt = DateTime.Parse(year + "-" + month + "-" + day + " " + hour + ":" + minite + ":" + second);
}
catch (WebException)
{
return DateTime.Parse("2011-1-1");
}
catch (Exception)
{
return DateTime.Parse("2011-1-1");
}
finally
{
if (wrp != null)
wrp.Close();
if (wrt != null)
wrt.Abort();
}
return dt; }
}

获取网络时间,返回一个DateTime对象,然后传给设置系统时间的方法,修改系统时间。下面是设置系统时间的代码:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Runtime; /// <summary>
/// 更新系统时间
/// </summary>
public class UpdateTime
{
//设置系统时间的API函数
[DllImport("kernel32.dll")]
private static extern bool SetLocalTime(ref SYSTEMTIME time); [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;
} /// <summary>
/// 设置系统时间
/// </summary>
/// <param name="dt">需要设置的时间</param>
/// <returns>返回系统时间设置状态,true为成功,false为失败</returns>
public static bool SetDate(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;
}
}

需要注意的时,在win8系统上需要以管理员身份来运行程序,否则是无法设置系统时间的。下面这段代码可以设置让程序默认以管理员身份运行:

 static void Main(string[] Args)
{
/**
* 当前用户是管理员的时候,直接启动应用程序
* 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
*/
//获得当前登录的Windows用户标示
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
//创建Windows用户主题
Application.EnableVisualStyles(); System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
//判断当前登录用户是否为管理员
if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
//如果是管理员,则直接运行 Application.EnableVisualStyles();
Application.Run(new Form1());
}
else
{
//创建启动对象
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
//设置运行文件
startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
//设置启动参数
startInfo.Arguments = String.Join(" ", Args);
//设置启动动作,确保以管理员身份运行
startInfo.Verb = "runas";
//如果不是管理员,则启动UAC
System.Diagnostics.Process.Start(startInfo);
//退出
System.Windows.Forms.Application.Exit();
}
}

搞定!

C# 实现网络时间同步功能的更多相关文章

  1. ubuntu设置系统时间与网络时间同步

    ubuntu设置系统时间与网络时间同步   Linux的时间分为System Clock(系统时间)和Real Time Clock (硬件时间,简称RTC).   系统时间:指当前Linux Ker ...

  2. ubuntu设置系统时间与网络时间同步和时区

    Linux的时间分为System Clock(系统时间)和Real Time Clock (硬件时间,简称RTC). 系统时间:指当前Linux Kernel中的时间. 硬件时间:主板上有电池供电的时 ...

  3. android命令行网络时间同步

    一.简介 Android基于Linux平台的开源手机操作系统. 二.原理 既然是Linux,那就应该支持linux的各种命令行,高度的可配置,但实验发现Android是Google的一个高度阉割版的l ...

  4. Linux系统将服务器时间与网络时间同步

    遇到一种情景,就是多台服务器之间的时间并不是同步的,有的快有的慢,这时候就要用到网络时间了, 登陆到服务器上,输入命令date可以查询服务器的时间,需要同步的时候需要安装ntpdate; 1.  安装 ...

  5. Linux的本地时间和网络时间同步

    Linux本地时间和网络时间不同步,更新了之后,重启还会变回去.可以通过一下方法修改并保存. 1.  安装ntpdate工具 sudo apt-get install ntpdate 2.  设置系统 ...

  6. 杂项:zabbix(WEB界面的提供分布式系统监视以及网络监视功能)

    ylbtech-杂项:zabbix(WEB界面的提供分布式系统监视以及网络监视功能) zabbix(音同 zæbix)是一个基于WEB界面的提供分布式系统监视以及网络监视功能的企业级的开源解决方案.z ...

  7. 基于【 centos7】二 || 系统时间与网络时间同步

    # date // 查看系统时间 #hwclock // 查看硬件时间 # yum -y install ntp ntpdate 安装ntpdate工具 # ntpdate cn.pool.ntp.o ...

  8. zabbix(一个基于WEB界面的提供分布式系统监视以及网络监视功能的企业级的开源解决方案)

    zabbix 是一个基于WEB界面的提供分布式系统监视以及网络监视功能的企业级的开源解决方案.zabbix能监视各种网络参数,保证服务器系统的安全运营:并提供灵活的通知机制以让系统管理员快速定位/解决 ...

  9. centos7设置系统时间与网络时间同步

    Linux的时间分为System Clock(系统时间)和Real Time Clock (硬件时间,简称RTC). 系统时间:指当前Linux Kernel中的时间. 硬件时间:主板上有电池供电的时 ...

随机推荐

  1. ruby md5 sha1 base64加密

    #md5加密 require 'md5' puts MD5.hexdigest('admin') #sha1加密 require 'digest/sha1' puts Digest::SHA1.hex ...

  2. ACM ICPC, Damascus University Collegiate Programming Contest(2018) Solution

    A:Martadella Stikes Again 水. #include <bits/stdc++.h> using namespace std; #define ll long lon ...

  3. db2,oracle,mysql ,sqlserver限制返回的行数

    不同数据库限制返回的行数的关键字如下: ①db2 select * from table fetch first 10 rows only; ②oracle select * from table w ...

  4. 居于mtk芯片安卓车机系统具体流程

    一:车机系统框架  MCU 功能  电源控制  Radio 控制(RDS)  按键检测(Panel/Remote/SW)  常见信号检查(倒车/大灯/刹车)  CAN 模块通讯  ARM- ...

  5. FastDFS+Nginx分布式文件系统部署安装

    安装: ##安装tracker.storage参考:http://www.cnblogs.com/zclzhao/p/5025229.html nginx代理设置参考:http://www.cnblo ...

  6. java maven 操作 收集的一些命令

    maven打包: mvn clean package -Dmaven.test.skip=true 运行jar: java -jar target/spring-boot-scheduler-1.0. ...

  7. enum SQLiteDateFormats

    DateTimeFormatInfo.CurrentInfo https://msdn.microsoft.com/en-us/library/system.globalization.datetim ...

  8. js的原型继承

    <script> //动物(Animal),有头这个属性,eat方法 //名字这个属性 //猫有名字属性,继承Animal,抓老鼠方法 function Animal(name){ thi ...

  9. LightOJ 1038 Race to 1 Again(概率dp+期望)

    https://vjudge.net/problem/LightOJ-1038 题意:给出一个数n,每次选择n的一个约数m,n=n/m,直到n=1,求次数的期望. 思路:d[i]表示将i这个数变成1的 ...

  10. Gym 101334F Feel Good

    http://codeforces.com/gym/101334 题意:给定一串数,求一个区间,使得该区间的所有数之和乘以该区间内最小的数的乘积最大. 思路:先预处理一下,计算出前缀和. 我们可以把每 ...