I have a C# Program that is supposed to be multi-OS compatible. It requires access to create a directory and get WMI Data, but that is only available if the program is ran as an Administrator. Otherwise, it fails.
Is there any command I can use to not run the program if it does not detect itself as being ran as an administrator? I tried adding a app.manifest and using "requireAdministrator", it prompts for login, but that appears to only work on Windows 7 and Vista, not XP.
Example:
if (isAdmin==0)
Console.WriteLine("Please run this as an administrator");
exit;
public static bool IsAdministrator()
{
WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity);
return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
}
public static bool RestartAsAdministrator(string filePath, string fileName, string errorCaption)
{
Process process = null;
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = Path.Combine(filePath, fileName);
if (Environment.OSVersion.Version.Major >= 5) //5 is XP and 6 is Vista and 7
processStartInfo.Verb = "runas";
processStartInfo.Arguments = "";
processStartInfo.WindowStyle = ProcessWindowStyle.Normal;
processStartInfo.UseShellExecute = true;
try
{
process = Process.Start(processStartInfo);
}
catch (Exception)
{
MessageBox.Show("Couldn't start as admin.\nPlease try manually by Right Clicking on " + Path.GetFileNameWithoutExtension(fileName) + " and selecting \"Run as administrator\"",
errorCaption + " Error", MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}
finally
{
if (process != null)
process.Dispose();
}
return true;
}
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
You can use this function to check if the current user (that starts your application) has administrator rights.
using System.Security.Principal;
...
bool IsAnAdministrator ()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal (identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
If you call this method and it returns false
you can show a message and/or close your application.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.