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. Singapore retailer will release this adidas NMD R1

    Select spots are restocking the adidas NMD Singapore this Friday, Feb 24th featuring three different ...

  2. forEach方法的实现

    var arr = [1, 23, 1, 1, 1, 3, 23, 5, 6, 7, 9, 9, 8, 5]; Array.prototype.forEach = Array.prototype.fo ...

  3. 1:3访问 servlet API 的两种方式(request,session等内置对象)

    1:解耦方式 2:耦合方式: ========================================== ========================================== ...

  4. Avito Cool Challenge 2018 Solution

    A. Definite Game 签. #include <bits/stdc++.h> using namespace std; int main() { int a; while (s ...

  5. uva1146 2-SAT问题

    题意大白书 二分答案,然后对于每个可能的答案,跑一遍2-SAT就好了. #include <iostream> #include <string.h> #include < ...

  6. 【android】移植IOS视图响应陀螺仪交互行为

    IOS有个很有趣味的特性:背景图片可以响应陀螺仪方向的变化,去改变X.Y轴上的值,从而让整个界面看着充满着灵性.具体步骤是:解锁苹果产品,在IOS7以上,摆动手势,观察桌面背景图片的变化. 刚好,我们 ...

  7. ubuntu 中启动SDK manager

    Android SDK安装后,目录结构如下: root@localhost:/home/ranxf/Android/Sdk/android-sdk-linux# ll 总用量 drwxrwxr-x r ...

  8. Linux环境下如何配置IP地址、MAC地址

    Linux环境下如何配置IP地址.MAC地址 1.配置IP地址 进入配置IP地址路径,进行修改即可 cd /etc/network vim interface 加入以下内容: iface eth0 i ...

  9. 如何解决Nginx php 50x 错误

    SEO反馈百度爬虫经常504,一般情况下是由nginx默认的fastcgi进程响应慢引起的,但也有其他情况,这里我总结了一些解决办法供大家参考.   方法/步骤 一般50x状态码问题分析: Nginx ...

  10. NOIP 2018退役祭

    Day 0 实在是没啥特别想干的...路上看了一下FE的小玉的第四周目的视频...然后到了之后整理了一下东西,然后被slr教着学了一下一个叫翻棋的东西,然后立刻就上瘾了...然后就听slr先生教我滑铁 ...