I have the following C# code:
public static void SetDateTime(System.DateTime datetime)
{
var systemNew = new SystemTime
{
wDay = (ushort)datetime.Day,
wMonth = (ushort)datetime.Month,
wYear = (ushort)datetime.Year,
wHour = (ushort)datetime.Hour,
wMinute = (ushort)datetime.Minute,
wSecond = (ushort)datetime.Second,
wMilliseconds = (ushort)datetime.Millisecond
};
// update system clock
NativeMethods.SetLocalTime(ref systemNew);
int errorCode = Marshal.GetLastWin32Error();
if (errorCode != 0)
{
Debug.WriteLine("SetDateTime error: {0}", errorCode);
}
}
internal struct SystemTime
{
internal ushort wDay;
internal ushort wDayOfWeek;
internal ushort wHour;
internal ushort wMilliseconds;
internal ushort wMinute;
internal ushort wMonth;
internal ushort wSecond;
internal ushort wYear;
}
internal static class NativeMethods
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int SetLocalTime(ref SystemTime lpSystemTime);
}
However, this gives me errorcode 87 everytime I call the method, any ideas?
Edit: I checked it on my local machine and it works fine there. It doesn't work with Remote Debugging from Visual Studio, even though the remote process runs under the same account as my local account and it's an administrator on that system.
The code which you posted don't contain any value of
datetimewhich you used to reproduce the error.For example
DateTime.Yearproperty can have the value between 1 and 9999 (see here). On the other side thewYearfield ofSYSTEMTIMEcan be between 1601 and 30827.So I recommend you first of all to verify old values of input struct which you use as the input to
SetLocalTime.UPDATED: It seems to me that I know the origin of the problem now. You defined
SystemTimewith the wrong order of fields as:but SYSTEMTIME is defined as