- /*&cls
- @echo off
- set "netpath=%systemroot%\Microsoft.NET\Framework"
- for /f "delims=" %%a in ('dir /ad /b "%netpath%\v?.*"') do (
- if exist "%netpath%\%%a\csc.exe" (
- set "cscpath=%netpath%\%%a\csc.exe"
- goto :0
- )
- )
- echo;未安装.Net Framework 2.0及其上版本组件或相关程序丢失&pause&exit
- :0
- if not exist $SetDateTime.exe ("%cscpath%" /out:$SetDateTime.exe "%~f0")
- echo;
- echo;手动运行$SetDateTime.exe
- ping -n 4 0 >nul&exit
- */
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Diagnostics;
- using System.Threading;
- class SetDateTime
- {
- private static byte[] result = new byte[512];
- static void Main(string[] args)
- {
- IPAddress ip = IPAddress.Parse(Dns.GetHostAddresses("time.nist.gov")[0].ToString());
- Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- try
- {
- clientSocket.Connect(new IPEndPoint(ip, 13));
- }
- catch
- {
- Console.WriteLine("连接服务器失败,程序将自动退出!");
- Thread.Sleep(3000);
- return;
- }
- int receiveLength = clientSocket.Receive(result);
- Match dtstr = Regex.Match(Encoding.ASCII.GetString(result, 0 ,receiveLength), @"\d+(-\d+){2}\s\d+(:\d+){2}");
- DateTime dt = DateTime.ParseExact(dtstr.ToString(), "yy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture).AddHours(8);
- Console.WriteLine("服务器当前日期时间为:{0}", dt.ToString());
- Process proc = new Process();
- proc.StartInfo.FileName = "cmd.exe";
- proc.StartInfo.Arguments = "/c date "+dt.ToShortDateString().ToString()+"&time "+dt.ToLongTimeString().ToString();
- proc.StartInfo.UseShellExecute = false;
- proc.StartInfo.RedirectStandardError = true;
- proc.Start();
- string err = proc.StandardError.ReadToEnd();
- Console.WriteLine(err != ""?err:"同步日期时间完成,请按任意键退出!");
- Console.ReadKey(true);
- }
- }
复制代码
|