The first method is to call the system API function to change the system time.
[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 retry IME );
Public static bool setlocaltimebystr (string timestr)
{
Bool flag = false;
Systemtime required IME = new systemtime ();
Datetime dt = convert. todatetime (timestr );
Required ime. wyear = convert. touint16 (Dt. year );
Required ime. wmonth = convert. touint16 (Dt. month );
Required ime. 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 function execution exception" + E. Message );
}
Return flag;
}
}
The second method is to use the process class to call the doc command to change the system time.
// A process class of the instance to start an independent process
PROCESS p = new process ();
// The process class has a startinfo attribute.
// Set the program name
P. startinfo. filename = "cmd.exe ";
// Set the program execution parameter "/C" to exit immediately after the command is executed.
P. startinfo. Arguments = "/c Date 2020-2-20 ";
// Close shell usage
P. startinfo. useshellexecute = false;
// Redirect standard input
P. startinfo. redirectstandardinput = true;
P. startinfo. redirectstandardoutput = true;
// Redirect error output
P. startinfo. redirectstandarderror = true;
// Set not to display the doc window
P. startinfo. createnowindow = true;
// Start
P. Start ();
// Obtain the command execution result from the output stream
Return P. standardoutput. readtoend ();
For more operations on the process class, refer
Http://msdn.microsoft.com/zh-cn/library/system.diagnostics.process_members (vs.80). aspx