更新系统时间

 

转载:http://www.cnblogs.com/Xingsoft-555/archive/2009/12/18/1627524.html

方法1:

namespace DABase.Models
{
    [StructLayout(LayoutKind.Sequential)]
    public struct SystemTime
    {
        public ushort wYear;
        public ushort wMonth;
        public ushort wDayOfWeek;
        public ushort wDay;
        public ushort wHour;
        public ushort wMinute;
        public ushort wSecond;
        public ushort wMiliseconds;
    }
    public class SetSystemDateTime
    {
        [DllImport("Kernel32.dll")]
        public static extern bool SetLocalTime(ref SystemTime sysTime);

        public static bool SetLocalTimeByStr(string timestr)
        {
            bool flag = false;
            SystemTime sysTime = new SystemTime();
            DateTime dt = Convert.ToDateTime(timestr);
            sysTime.wYear = Convert.ToUInt16(dt.Year);
            sysTime.wMonth = Convert.ToUInt16(dt.Month);
            sysTime.wDay = Convert.ToUInt16(dt.Day);
            sysTime.wHour = Convert.ToUInt16(dt.Hour);
            sysTime.wMinute = Convert.ToUInt16(dt.Minute);
            sysTime.wSecond = Convert.ToUInt16(dt.Second);
            try
            {
                flag = SetSystemDateTime.SetLocalTime(ref sysTime);
            }
            catch (Exception e)
            {
                Console.WriteLine("SetSystemDateTime函数执行异常" + e.Message);
            }
            return flag;
        }
    }
}

方法2 :(未验证)  就是利用Process类调用DOC命令更改系统时间

//实例一个Process类,启动一个独立进程 
             Process p = new Process(); 
               //Process类有一个StartInfo属性 
             //设定程序名 
             p.StartInfo.FileName = "cmd.exe";
             //设定程式执行参数    “/C”表示执行完命令后马上退出
             p.StartInfo.Arguments = "/c date 2020-2-20";  
              //关闭Shell的使用   
            p.StartInfo.UseShellExecute = false;    
            //重定向标准输入      
            p.StartInfo.RedirectStandardInput = true;  
            p.StartInfo.RedirectStandardOutput = true; 
              //重定向错误输出   
           p.StartInfo.RedirectStandardError = true;   
              //设置不显示doc窗口  
            p.StartInfo.CreateNoWindow = true;           
            //启动 
            p.Start(); 

          //从输出流取得命令执行结果 
           return p.StandardOutput.ReadToEnd();

  

 

posted @ 2017-09-18 11:19  人生为卒  阅读(178)  评论(0编辑  收藏  举报