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. Action<>和Func<> 区别

    其实他们两个都是委托[代理]的简写形式. 一.[action<>]指定那些只有输入参数,没有返回值的委托 Delegate的代码: public delegate void myDeleg ...

  2. 34sqlite

    sqlite,本地数据库.主要运用在小型的程序,传送方便(如发送附带数据库的程序,但MySQL有点大,或许没安装). 如何创建本地数据库? 1.新建一个.txt的文本文件. 2.直接将后缀名有.txt ...

  3. MySQL基础语句【学习笔记】

    放在这里,以备后查. 1. 数据库, 数据库服务器, 数据库语言 数据库,是持久性数据的集合,供给定企业的应用程序系统使用,并且由一个数据库管理系统来管理: 数据库服务器,又称数据库管理系统,用来管理 ...

  4. 2017-2018-2 20165207 实验三《敏捷开发与XP实践》实验报告

    java 实验三 实验报告 实验内容 代码规范 不规范的代码可能妨碍阅读,在粘贴下来老师在云班课中设置的提交点一的代码之后,我首先使用了IDEA中Code选项卡的Reformat Code功能规范代码 ...

  5. asp.net 获取mp3 播放时长

    1 Shell32 //添加引用:COM组件的Microsoft Shell Controls And Automation //然后引用 using Shell32; //如果出现“无法嵌入互操作类 ...

  6. redis的过期策略以及内存淘汰机制

    redis采用的是定期删除+惰性删除策略. 为什么不用定时删除策略? 定时删除,用一个定时器来负责监视key,过期则自动删除.虽然内存及时释放,但是十分消耗CPU资源.在大并发请求下,CPU要将时间应 ...

  7. spring Security简介

    它是spring的权限管理框架

  8. AngularJS Toaster

    AngularJS Toaster 是 AngularJS 的扩展,实现了无堵塞消息通知.该项目对 Toastr 进行改造,原来的 Toastr 只支持 jQuery,而 AngularJS Toas ...

  9. Vue学习笔记一:使用vue-cli 创建开发环境

    第一步:安装Node.js 点击此处下载    选择对应的安装包,进行安装. 第二步:安装淘宝镜像 有一个问题,使用 npm 会导致网速很慢,对于大陆用户,建议将 npm 的注册表源设置为国内的镜像, ...

  10. vijos 1082

    描述 东非大裂谷中有一片神秘的丛林,是全世界探险家的乐园,著名黄皮肤探险家BB一直想去试试.正好我国科学家2005年4月将首次对东非大裂谷进行科考,BB决定随科考队去神秘丛林探险.在出发之前,他搜集了 ...