"Willy Denoyette [MVP]" <wi*************@telenet.be> wrote in message
news:eE**************@TK2MSFTNGP14.phx.gbl...
"Indrani" <no*********@rediffmail.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...I am working on a C# console application. How can we set the system
date in C#.
Rgds,
Indrani
1. Use PInvoke to call Win32 API SetSystemTime, or
2. use System.Management classes with WMI class Win32_OperatingSystem and
call SetDateTime on that class.
Both require that the caller has been granted SeSystemTimePrivilege and
that this privilege is enabled.
The second is only available on XP and higher.
Willy.
Here is how using PInvoke...
class Tester
{
[System.Runtime.InteropServices.DllImport("kernel32 ", SetLastError =
true)]
private static extern bool GetSystemTime(out SYSTEMTIME systemTime);
[System.Runtime.InteropServices.DllImport("kernel32 ", SetLastError =
true)]
private static extern bool SetSystemTime(ref SYSTEMTIME systemTime);
struct SYSTEMTIME {
internal short wYear;
internal short wMonth;
internal short wDayOfWeek;
internal short wDay;
internal short wHour;
internal short wMinute;
internal short wSecond;
internal short wMilliseconds;
}
static void Main()
{
SYSTEMTIME st;
if(GetSystemTime(out st))
{
st.wHour = 13; //Beware SYSTEMTIME is in UTC time format!!!!!
if(SetSystemTime(ref st))
Console.WriteLine("success");
else
Console.WriteLine(System.Runtime.InteropServices.M arshal.GetLastWin32Error());
}
else
Console.WriteLine("GetSystemTime failed: {0}",
System.Runtime.InteropServices.Marshal.GetLastWin3 2Error());
}
}
Willy.