SynchronizeSystemClock requires administrator privilege

0 votes
asked Jul 24, 2013 by Rebex KB (8,380 points)
edited Jul 24, 2013

I'm trying to synchronize time on local computer using the following method:

Ntp.SynchronizeSystemClock("pool.ntp.org");

but it throws the following error:

Rebex.Net.NtpException: The required privilege to set system time is not held by the process. Try running as administrator.

How to get rid of this exception?

Applies to: Rebex Time

1 Answer

0 votes
answered Jul 24, 2013 by Jan Sotola (17,310 points)
edited Jul 24, 2013
 
Best answer

The exception is correct - setting a system time (as being done within the SynchronizeSystemClock method) is an operation, which really requires elevated privileges on Windows Vista or newer.

The simplest solution is to detect, whether the application runs in administrator mode and if it does not, re-run the application in the elevated mode. It can be accomplished using the following method:

public bool ElevateIfNeeded()
{
    // determine wheher we currenly have admin privileges
    WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
    bool isElevated = pricipal.IsInRole(WindowsBuiltInRole.Administrator);

    // if we do, then nothing needs to be done
    if (isElevated)
        return true;

    // inform he user we are going to try elevating the application
    MessageBox.Show("In order to be able to synchronize local time with the server, this application first needs to be elevated to gain administrator permissions.", "Synchronize");

    // start a new instance of the application in elevated mode
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.Verb = "runas";
    startInfo.FileName = Process.GetCurrentProcess().MainModule.FileName;
    startInfo.Arguments = "-sync";
    try
    {
        Process.Start(startInfo);
        Application.Exit();
    }
    catch (Win32Exception)
    {
        // elevation not allowed
    }

    return false;
}

Elevation without exiting the current application is quite more complicated. It is described e.g. in the MSKB981778 article.

Note: There are also articles advising to override the time-setting restrictions by setting Windows group policy, but we've not checked, whether it really helps.

...