ClickOnce发布方便快捷,可实现程序远程下载、安装、自动更新等功能,但是还是有些细节做的不到位。比方服务器更新了一个新版本1.0.0.22,这时客户端运行程序检查到有新版本更新,如果不小心点击“跳过”按钮,那么再次打开程序的时候将不会再去检查是否有新版本。也就是说
新版本1.0.0.22再也更新不到了,必须等待下一个
新版本的发布。针对这种情况我们需要在程序中添加一个手动更新的功能,以下是网上找到的方法,特此分享给大家。
方法一:
该方法出至microsoft官方文档,以下是C#代码:
using System.Deployment.Application;
private void InstallUpdateSyncWithInfo()
{
UpdateCheckInfo info = null;
if (ApplicationDeployment.IsNetworkDeployed)
{
ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
try
{
info = ad.CheckForDetailedUpdate();
}
catch (DeploymentDownloadException dde)
{
MessageBox.Show("The new version of the application cannot be downloaded at this time. \n\nPlease check your network connection, or try again later. Error: " + dde.Message);
return;
}
catch (InvalidDeploymentException ide)
{
MessageBox.Show("Cannot check for a new version of the application. The ClickOnce deployment is corrupt. Please redeploy the application and try again. Error: " + ide.Message);
return;
}
catch (InvalidOperationException ioe)
{
MessageBox.Show("This application cannot be updated. It is likely not a ClickOnce application. Error: " + ioe.Message);
return;
}
if (info.UpdateAvailable)
{
Boolean doUpdate = true;
if (!info.IsUpdateRequired)
{
DialogResult dr = MessageBox.Show("An update is available. Would you like to update the application now?", "Update Available", MessageBoxButtons.OKCancel);
if (!(DialogResult.OK == dr))
{
doUpdate = false;
}
}
else
{
// Display a message that the app MUST reboot. Display the minimum required version.
MessageBox.Show("This application has detected a mandatory update from your current " +
"version to version " + info.MinimumRequiredVersion.ToString() +
". The application will now install the update and restart.",
"Update Available", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
if (doUpdate)
{
try
{
ad.Update();
MessageBox.Show("The application has been upgraded, and will now restart.");
Application.Restart();
}
catch (DeploymentDownloadException dde)
{
MessageBox.Show("Cannot install the latest version of the application. \n\nPlease check your network connection, or try again later. Error: " + dde);
return;
}
}
}
}
}
官网地址:
https://msdn.microsoft.com/zh-cn/library/ms404263.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
方法二:
该方法是elearning视频上记录下来的,以下是C#代码:
private void InstallUpdateSyncWithInfo()
{
if (ApplicationDeployment.IsNetworkDeployed == true)
{
ApplicationDeployment thisDeployment = ApplicationDeployment.CurrentDeployment;
this.Text = "正在检测更新...";
if (thisDeployment.CheckForUpdate() == true)
{
if (MessageBox.Show("检测到有新的版本可以进行更新,现在需要更新吗?", "选择是否要进行更新", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
this.Text = "正在更新中";
thisDeployment.Update();
MessageBox.Show("更新完毕,将要重启程序!");
Application.Restart();
}
else
{
this.Text = Application.ProductName + " " + Application.ProductVersion;
}
}
else
{
MessageBox.Show("并没有新的版本进行更新!");
}
}
else
{
MessageBox.Show("这不是网络发布的程序");
}
}