[C#.NET] ClickOnce 佈署 檢查更新

[C#.NET] ClickOnce 佈署 檢查更新

續上篇,使用ClickOnce佈署後,我們還需要一個機制用來檢查是否有新的組件;還記得預設的更新機制是軟體開啟前或是軟體關閉後,我們不能確保使用者都會執行軟體關閉或重新開啟的動作,這時候就在軟體執行期間去檢查有無更新組件。

會用到的命名空間:System.Deployment.Application

會用到的類別:ApplicationDeployment 類別

 

下段程式碼是用timer來檢查有無新版

 


bool _updateFlag = false;
private void UpdateApplication()
{
    if (!ApplicationDeployment.IsNetworkDeployed)
        return;

    this.timer1.Enabled = true;
    this.timer1.Interval = 60000;
    this.timer1.Start();

    ApplicationDeployment deploy = ApplicationDeployment.CurrentDeployment;
    bool isUpdate = ApplicationDeployment.CurrentDeployment.CheckForUpdate();
    if (isUpdate && (this._updateFlag == false))
    {
        DialogResult updateResult = MessageBox.Show("線上有新的版本,是否馬上更新版本?", "更新通知", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

        if (updateResult == DialogResult.Yes)
        {
            this._updateFlag = true;
            this.timer1.Stop();
            deploy.UpdateProgressChanged += new DeploymentProgressChangedEventHandler(deploy_UpdateProgressChanged);
            deploy.UpdateCompleted += new AsyncCompletedEventHandler(deploy_UpdateCompleted);
            deploy.UpdateAsync();
        }
        else
        {
            //TODO:不馬上通知的動作
        }
    }
}

void deploy_UpdateCompleted(object sender, AsyncCompletedEventArgs e)
{
    //更新完成
    MessageBox.Show("更新完畢,將重新啟動!");
    Application.Restart();
}

void deploy_UpdateProgressChanged(object sender, DeploymentProgressChangedEventArgs e)
{
    //更新狀態更新
    this.progressBar1.Value = e.ProgressPercentage;
    Application.DoEvents();
}

private void timer1_Tick(object sender, EventArgs e)
{
    if (!this._updateFlag)
        UpdateApplication();
    else
        timer1.Stop();
}

private void Form1_Load(object sender, EventArgs e)
{
    UpdateApplication();
}



很簡單的一個範例實作,這樣一來專案若未用ClickOnce網路佈署就不會觸動timer不斷的檢查,只要安裝該軟體的用戶則會觸動timer檢查

 

 

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo