最近写了一个控制台程序,将程序的相关信息注册到注册表中。但是运行的时候提示写注册表被拒。电脑的当前用户没有管理员的权限。
如何给控制台程序赋管理员的权限呢?
给程序添加 .manifest 文件:应用程序的Manifests则用于描述隔离应用程序,它管理着此应用程序在运行时要绑定的共享的并行组件的名字、版本。该Manifests可以作为一个文件(.manifest文件)存储在应用程序相同的目录下,也可以作为一种资源嵌入在可执行文件内部(Embed Manifest)。
1、通过属性界面加载。
首先检查 VS2010 的【Properties】节点下是否有【app.manifest】这个文件,如果没有的话双击【Properties】节点。弹出属性界面。
勾选中【Security】页面中的【Enable ClickOnce Security Settings】节点(如下图)。会在【Properties】下就有自动生成【app.manifest】文件(如右上图)。
双击打开【app.manifest】文件,将
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
改为
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
asInvoker : 应用程序就是以当前的权限运行。
highestAvailable: 以当前用户可以获得的最高权限运行。
requireAdministrator: 以系统管理员权限运行。
修改后的文件如下:
然后再勾去【Security】中【Enable ClickOnce Security Settings】后,重新编译即可。
2、通过添加新项添加:
通过这种方式添加的app.manifest不是位于【Properties】节点下;而是位于【Properties】的同级目录下。
双击打开【app.manifest】文件,将
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
改为
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
即可。
附:如果是WinFrom 窗体应用程序:可以通过代码来实现“以管理员身份运行”(转)
static void Main(string[] Args)
{
/**
* 当前用户是管理员的时候,直接启动应用程序
* 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
*/
//获得当前登录的Windows用户标示
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
//创建Windows用户主题
Application.EnableVisualStyles();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
//判断当前登录用户是否为管理员
if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
//如果是管理员,则直接运行
Application.EnableVisualStyles();
Application.Run(new Form1());
}
else
{
//创建启动对象
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
//设置运行文件
startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
//设置启动参数
startInfo.Arguments = String.Join(" ", Args);
//设置启动动作,确保以管理员身份运行
startInfo.Verb = "runas";
//如果不是管理员,则启动UAC
System.Diagnostics.Process.Start(startInfo);
//退出
System.Windows.Forms.Application.Exit();
}
}