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.