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. c#通过webrequest请求远程http服务时出现的问题

    用WebRequest和WebClient,两种方式,请求一个由http服务发布的应用,结果出现异常. 有三种,1.System.Net.WebException: 服务器提交了协议冲突. Secti ...

  2. rails 日期取值

    获取当前时间 当前时间 Time.now UTC时间, 国际标准时间 Time.now.utc 日相关 今日开始时间00:00:00 Time.now.beginning_of_day => 2 ...

  3. 【知识总结】Java类初始化顺序说明

    微信公众号:努力编程的小猪如有问题或建议,请公众号留言 Java类初始化顺序说明 一个类中包含如下几类东西,他们前后是有顺序关系的 静态属性:static 开头定义的属性 静态方法块: static ...

  4. 通过自动回复机器人学Mybatis:MySQL脚本 + db >> dao >> service >> servlet

    留着参考 makeData.sql delimiter // create procedure make_data() begin declare i int ; do insert into mes ...

  5. A8几种内存

    1.SD卡(程序可写入,当成最次硬盘来用) 2.nandflash(程序可写入,当成一般硬盘来用) 3.DDR2(当A8板子的内存条来用)

  6. CSS3动画库——animate.css

    初见animate.css的时候,感觉很棒,基本上很多常用的CSS3动画效果都帮我们写好了,所以想要哪一种效果直接就可以拿过来用,甚是方便: 效果展示官网:http://daneden.github. ...

  7. ubuntu16.04下安装TensorFlow(GPU加速)----详细图文教程【转】

    本文转载自:https://blog.csdn.net/zhaoyu106/article/details/52793183 le/details/52793183 写在前面 一些废话 接触深度学习已 ...

  8. HDU6447 网络赛 YJJ's Salesman(DP + 线段树)题解

    思路:若用dp[i][j]表示走到(i,j)的最大值,那么dp[i][j] = max(dp[i - 1][j],dp[i][j - 1],dp[i - 1][j - 1] + v),显然O(n^2) ...

  9. UVa 10294 项链和手镯(polya)

    https://vjudge.net/problem/UVA-10294 题意: 手镯可以翻转,但项链不可以.输入n和t,输出用t种颜色的n颗珠子能制作成的项链和手镯的个数. 思路: 经典等价类计数问 ...

  10. ubuntu 14.04 (desktop amd 64) 查看配置参数

    硬盘型号 sudo hdparm -i /dev/sda |grep "Model"   硬盘数量大小 sudo fdisk -l |grep "Disk /dev/sd ...