我有一个Excel VSTO加载项,该加载项通过ClickOnce每24小时更新一次。效果很好。
我想提供一个按钮,用户可以在其中立即手动检查更新。我遵循了instructions provided in the documentation。我的代码如下:(暂时忽略注释部分)
Sub TryUpdateApp()
If (ApplicationDeployment.IsNetworkDeployed) Then
Dim Deployment As ApplicationDeployment = ApplicationDeployment.CurrentDeployment
Dim Info As UpdateCheckInfo = Nothing
'Try
' Dim AppIdentity As New ApplicationIdentity(Deployment.UpdatedApplicationFullName)
' Dim UnrestrictedPerms As New Security.PermissionSet(Security.Permissions.PermissionState.Unrestricted)
' Dim AppTrust As New Security.Policy.ApplicationTrust(AppIdentity) With {
' .DefaultGrantSet = New Security.Policy.PolicyStatement(UnrestrictedPerms),
' .IsApplicationTrustedToRun = True,
' .Persist = True
' }
' Security.Policy.ApplicationSecurityManager.UserApplicationTrusts.Add(AppTrust)
'Catch ex As Exception
' 'log error
'End Try
Try
Info = Deployment.CheckForDetailedUpdate()
Catch dde As DeploymentDownloadException
MsgBox($"The new version of App cannot be downloaded at this time.{vbNewLine}Please check your network connection, or try again later. Error: {dde.Message}", vbExclamation Or vbOKOnly)
Exit Sub
Catch ioe As InvalidOperationException
MsgBox($"This application cannot be updated. It is likely not a ClickOnce application. Error: {ioe.Message}", vbCritical Or vbOKOnly)
Exit Sub
End Try
Try
If (Info.UpdateAvailable) Then
Try
Deployment.Update()
MsgBox("App has been upgraded. Please restart Excel to apply changes.", vbInformation Or vbOKOnly)
Catch dde As DeploymentDownloadException
MsgBox($"Unable to install the latest version of App: download failed.{vbNewLine}Please check your network connection, or try again later.", vbCritical Or vbOKOnly)
Exit Sub
Catch tnge As TrustNotGrantedException
MsgBox("Unable to install the latest version of App: trust not granted.", vbExclamation Or vbOKOnly)
Exit Sub
End Try
Else
MsgBox("The latest version of App is already installed.", vbInformation Or vbOKOnly)
End If
Catch ex As Exception
MsgBox("Unable to install the latest version of App: unknown error.")
Exit Sub
End Try
Else
Throw New ApplicationException("Application is not network deployed.")
End If
End Sub
尽管它可以准确指示何时“已经安装了最新版本的App。”,但如有必要,它将无法更新,并抛出TrustNotGrantedException: User has refused to grant required permissions to the application.
。
[第一个有趣的事情是,此异常是由“无法安装最新版本的应用程序:未知错误。”而不是“无法安装最新版本的应用程序:未授予信任”捕获的。
然后找到this thread,它对应于上面代码的注释部分。当我取消注释并运行该子程序时,它似乎可以正常工作,因为我收到“应用程序已升级。请重新启动Excel以应用更改”。但是,当我随后重新启动Excel并再次运行Sub时,出现“应用程序未通过网络部署”。
我该如何解决? (任何C#代码都可以)
首先,尝试在受信任的站点列表中添加应用程序URL。
根据MSDN,如果发生以下情况,则抛出TrustNotGrantedException
:
应用程序使用权限提升,并且用户拒绝提升信任的请求;或
该应用程序使用“受信任的应用程序部署”,并且用于对应用程序进行签名的数字证书未在本地计算机上列为受信任的发布者。如果您已对应用程序部署了更新,并且该更新使用的权限比以前的版本多,并且ClickOnce引发TrustNotGrantedException,将不会安装新版本。
由于这是一个完全信任的应用程序,因此您的用户是否具有管理员权限,是否有任何需要管理员权限的操作?
您的证书是来自CA还是VS生成的测试证书?如果那是测试证书,则需要检查它是否已添加到“信任发布者”列表中。
更多信息,请参见How to: Add a Trusted Publisher to a Client Computer for ClickOnce Applications。