WPF以Clickonce方式发布后使用管理员身份运行

时间:2023-03-08 20:23:38

WPF的程序,在发布时采用的Clickonce方式发布,Win7的用户安装完成之后,发现执行某些操作的时候会导致程序异常。在排查后发现,是权限问题导致。如图:

WPF以Clickonce方式发布后使用管理员身份运行

是执行File.Move时引发的异常:对路径的访问被拒绝。

首先想到的是:右键-->以管理员身份运行,但是Clickonce发布过的程序,右键菜单中是没有这个选项的。

那怎么才能以管理员身份运行呢?

按照搜索的答案,

1)右键项目属性

2)选择安全性,勾选“启用ClickOnce安全设置”

3)在项目的Properties文件夹中,找到app.mainfest

4)将节点

<requestedExecutionLevel level="asInvoker" uiAccess="false" /> 
改为
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

5)回到项目属性中的安全性选项,去掉“启用ClickOnce安全设置”。

6)保存,编译

一直到现在,都还是顺利的,

7)发布。。。报错!

错误 6 ClickOnce does not support the request execution level 'requireAdministrator'.

WPF以Clickonce方式发布后使用管理员身份运行

这是什么狗屁错?继续搜索,搜索的结果都是说要在项目属性页面中,安全性选项卡中的“启用ClickOnce安全设置”去掉勾选。

那就去掉勾选,然后重新发布,仍旧报错,回到安全性选项卡中发现,“启用ClickOnce安全设置”又被勾选上了。

奇怪了。。。。。

网上搜索了N久,终于找到了解决办法

为了使得发布之后的程序能够获得管理员的权限

1)app.mainfest文件中

<requestedExecutionLevel level="asInvoker" uiAccess="false" /> 
节点的值设置为 asInvoker

2)在App.cs中增加以下代码:

        /// <summary>
/// 检查是否是管理员身份
/// </summary>
private void CheckAdministrator()
{
var wi = WindowsIdentity.GetCurrent();
var wp = new WindowsPrincipal(wi); bool runAsAdmin = wp.IsInRole(WindowsBuiltInRole.Administrator); if (!runAsAdmin)
{
// It is not possible to launch a ClickOnce app as administrator directly,
// so instead we launch the app as administrator in a new process.
var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase); // The following properties run the new process as administrator
processInfo.UseShellExecute = true;
processInfo.Verb = "runas"; // Start the new process
try
{
Process.Start(processInfo);
}
catch (Exception ex)
{
ex.WriteLog();
} // Shut down the current process
Environment.Exit();
}
}

3)重写 OnStartup 函数

        protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e); CheckAdministrator();
//如果不是管理员,程序会直接退出,并使用管理员身份重新运行。
StartupUri = new Uri("MainWindow.xaml", UriKind.RelativeOrAbsolute);
}

4)保存,重新生成,发布

加入上面的代码之后,重新使用ClickOnce方式发布,安装。在运行的时候,会弹出“您想允许来自未知发布者的以下程序对此计算机进行更改吗”的对话框,点击“是” 程序就会以管理员身份运行了。

参考链接:http://www.codeproject.com/Tips/627850/ClickOnce-deployment-vs-requestedExecutionLevel-eq