我的帐户具有管理权限。我使用powershell在Windows 7 Enterprise VM上访问WMI,如下所示:
Get-WmiObject -Namespace root\SecurityCenter2 -Class AntiVirusProduct -ComputerName $computername和C#,如下所示:
string computer = Environment.MachineName;
string wmipath = @"\\" + computer + @"\root\SecurityCenter2";
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmipath,
"SELECT * FROM AntivirusProduct");
ManagementObjectCollection instances = searcher.Get();
//MessageBox.Show(instances.Count.ToString());
foreach (ManagementObject queryObj in instances)
{
return queryObj[type].ToString();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}但是,Powershell中的代码总是有效的,但C#中的代码只有在我以管理员身份显式运行程序时才有效。我是否可以在C#代码中添加任何内容,以便在不以管理员身份显式启动C#程序的情况下,以具有管理权限的用户身份运行它?
发布于 2012-12-18 02:13:04
您可以通过编辑manifest (与C#可执行文件位于同一目录中的XML文件)来强制UAC提示,而不必显式地“以管理员身份运行”。
请参阅"How to force my .NET App to run as administrator on Windows 7?"的StackOverflow答案。
发布于 2012-12-18 02:18:19
通常,当我的应用程序只能从计算机管理员运行时,我会使用以下方法来验证管理员权限:
public static bool HasAdministrativeRight()
{
WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}在我的代码的主要部分(窗体或控制台应用程序)
if (!HasAdministrativeRight())
{
if (RunElevated(""))
{
Application.Exit();
}
}以提升的方式运行的代码:
private static bool RunElevated(string args)
{
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.Verb = "runas";
processInfo.FileName = Application.ExecutablePath;
processInfo.Arguments = args;
try
{
Process.Start(processInfo);
return true;
}
catch (Exception)
{
//Do nothing. Probably the user canceled the UAC window
}
return false;
}https://stackoverflow.com/questions/13918495
复制相似问题