0

我有以下 C# 代码:

 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);
}

但是,每次我调用该方法时,这都会给我错误代码 87,有什么想法吗?

编辑:我在我的本地机器上检查了它,它在那里工作正常。 它不适用于 Visual Studio 中的远程调试,即使远程进程在与我的本地帐户相同的帐户下运行并且它是该系统上的管理员。

4

1 回答 1

2

您发布的代码不包含您用来重现错误的任何值。datetime

例如DateTime.Year,属性的值可以在 1 到 9999 之间(参见此处)。另一方面, 的wYear字段SYSTEMTIME可以在 1601 和 30827 之间。

因此,我建议您首先验证您用作输入的输入结构的旧值SetLocalTime

更新:在我看来,我现在知道问题的根源了。您SystemTime错误的字段顺序定义为:

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;
}

SYSTEMTIME定义为

typedef struct _SYSTEMTIME {
  WORD wYear;
  WORD wMonth;
  WORD wDayOfWeek;
  WORD wDay;
  WORD wHour;
  WORD wMinute;
  WORD wSecond;
  WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME;
于 2012-05-25T08:26:19.910 回答