核心代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace TestServerTime
{
public class ServerInfo
{
public static string GetHostName()
{
return Dns.GetHostName();
}
public static string GetLocalIP()
{
string ip = "";
try
{
string HostName = Dns.GetHostName(); //得到主机名
IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
for (int i = 0; i < IpEntry.AddressList.Length; i++)
{
//从IP地址列表中筛选出IPv4类型的IP地址
//AddressFamily.InterNetwork表示此IP为IPv4,
//AddressFamily.InterNetworkV6表示此地址为IPv6类型
if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
{
ip = IpEntry.AddressList[i].ToString();
}
}
}
catch (Exception ex)
{
throw ex;
}
return ip;
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool SetLocalTime(ref SYSTEMTIME lpSystemTime);
[StructLayout(LayoutKind.Sequential)]
internal struct SYSTEMTIME
{
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek; // ignored for the SetLocalTime function
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMilliseconds;
}
public static bool SetLocalTimeByStr(string timestr)
{
bool flag = false;
SYSTEMTIME sysTime = new SYSTEMTIME();
string SysTime = timestr.Trim(); //此步骤多余,为方便程序而用直接用timestr即可
sysTime.wYear = Convert.ToUInt16(SysTime.Substring(0, 4));
sysTime.wMonth = Convert.ToUInt16(SysTime.Substring(4, 2));
sysTime.wDay = Convert.ToUInt16(SysTime.Substring(6, 2));
sysTime.wHour = Convert.ToUInt16(SysTime.Substring(8, 2));
sysTime.wMinute = Convert.ToUInt16(SysTime.Substring(10, 2));
sysTime.wSecond = Convert.ToUInt16(SysTime.Substring(12, 2));
//注意:
//结构体的wDayOfWeek属性一般不用赋值,函数会自动计算,写了如果不对应反而会出错
//wMiliseconds属性默认值为一,可以赋值
try
{
flag = SetLocalTime(ref sysTime);
}
//由于不是C#本身的函数,很多异常无法捕获
//函数执行成功则返回true,函数执行失败返回false
//经常不返回异常,不提示错误,但是函数返回false,给查找错误带来了一定的困难
catch (Exception ex1)
{
Console.WriteLine("SetLocalTime函数执行异常" + ex1.Message);
}
return flag;
}
}
}调用代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestServerTime
{
class Program
{
static void Main(string[] args)
{
string destTime = "2015-11-12 15:09:24";
SetServerTime(destTime);
System.Console.WriteLine( DateTime.Now.ToLocalTime());
System.Console.ReadLine();
}
public static void SetServerTime(string destTime)
{
ServerInfo.SetLocalTimeByStr(DateTime.Parse(destTime).ToString("yyyyMMddHHmmss"));
}
}
}本文出自 “爱工作爱生活” 博客,请务必保留此出处http://4453154.blog.51cto.com/4443154/1712241
原文:http://4453154.blog.51cto.com/4443154/1712241