您的位置:首页 > 编程语言 > C#

C#Winfrom调用CMD实现一键同步系统时间

2018-08-28 13:17 561 查看

命名空间

using System.Diagnostics;

获取网络时间(类):

public static string GetNetDateTime()
{
WebRequest request = null;
WebResponse response = null;
WebHeaderCollection headerCollection = null;
string datetime = string.Empty;
try
{
request = WebRequest.Create("https://www.baidu.com");
request.Timeout = 3000;
request.Credentials = CredentialCache.DefaultCredentials;
response = (WebResponse)request.GetResponse();
headerCollection = response.Headers;
foreach (var h in headerCollection.AllKeys)
{ if (h == "Date") { datetime = headerCollection[h]; } }
return datetime;
}
catch (Exception) { return datetime; }
finally
{
if (request != null)
{ request.Abort(); }
if (response != null)
{ response.Close(); }
if (headerCollection != null)
{ headerCollection.Clear(); }
}
}

按钮代码:

private void button1_Click(object sender, EventArgs e)//一键同步按钮
{
string dt = GetNetDateTime();//引用方法
string dtdate = Convert.ToDateTime(dt).ToString("yyyy-MM-dd");//获取日期
string dttime = Convert.ToDateTime(dt).ToString("HH:mm:ss");//获取时间
string dos1 = "date " + dtdate;//命令1
string dos2 = "time " + dttime;//命令2
string box1 = DateTime.Now.ToString();//获取校准前时间

System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
p.StartInfo.CreateNoWindow = true;//不显示程序窗口
p.Start();//启动程序
//向cmd窗口发送输入信息
p.StandardInput.WriteLine(dos1 + "&" + dos2 + "&exit");
p.StandardInput.AutoFlush = true;
//p.StandardInput.WriteLine("exit");
//向标准输入写入要执行的命令。这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死
//同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令
//获取cmd窗口的输出信息
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();//等待程序执行完退出进程
p.Close();
string box2 = DateTime.Now.ToString();//获取校准后时间
string box3 = "时间校准成功!\r校准前:" + box1 + ".\r校准后:" + box2 + ".";
box3 = box3.Replace("/", "-");
box3 = box3.Replace(" ", ",");
MessageBox.Show(box3, "计算机时间校准", MessageBoxButtons.OK, MessageBoxIcon.Information);//弹出提示框
}

代码来源自互联网,我只做些修改与应用。出处如下:
获取网络日期时间
https://zhidao.baidu.com/question/1695321825523478548.html
C#程序调用cmd.exe执行命令
https://www.geek-share.com/detail/2617806201.html

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: