Menü Schließen

Check if Current User has Admin Rights and Restart Application with Elevated Rights

The following code snippet checks if the current user as administrator rights:

/// <summary> 
/// Checks if user has administrator rights 
/// </summary> 
public static bool UserIsAdmin() 
{ 
  WindowsIdentity identity = WindowsIdentity.GetCurrent(); 
  WindowsPrincipal principal = new WindowsPrincipal(identity); 
  return principal.IsInRole(WindowsBuiltInRole.Administrator); 
}

If the application requires administrator rights for an operation, the following function can be used to restart the application with elevated rights:

/// <summary>
/// Restarts the current application with admin rights.
/// </summary>
public static bool RunElevated()
{
  string args = string.Empty;
  string[] argsArray = Environment.GetCommandLineArgs();

  // First entry of the array must be ignored!
  for (int i = 1; i < argsArray.Length; i++)
  {
    if (!string.IsNullOrEmpty(args))
      args += " ";
    args += argsArray[i];
  }
  return RunElevated(System.Windows.Forms.Application.ExecutablePath, args);
}

/// <summary>
/// Restarts any application with admin rights.
/// </summary>
public static bool RunElevated(string fileName, string args)
{
  ProcessStartInfo processInfo = new ProcessStartInfo();
  processInfo.Verb = "runas";
  processInfo.FileName = fileName;
  processInfo.Arguments = args;

  try
  {
    Process.Start(processInfo);
    return true;
  }
  catch
  {
    return false;
  }
}

If the current user has no administrator rights, the Windows login-window appears and you can enter admin credentials.

Ähnliche Beiträge

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert