[英]How can I prevent my program from running if it is not ran in Administrative mode? XP and Windows 7
I have a C# Program that is supposed to be multi-OS compatible. 我有一个C#程序,应该是多操作系统兼容的。 It requires access to create a directory and get WMI Data, but that is only available if the program is ran as an Administrator.
它需要访问权限才能创建目录并获取WMI数据,但只有在以管理员身份运行程序时才可以使用。 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.
我尝试添加app.manifest并使用“requireAdministrator”,它会提示登录,但这似乎只适用于Windows 7和Vista,而不是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. 如果您调用此方法并返回
false
,则可以显示消息和/或关闭应用程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.