ApplicationDeployment.UpdateAsync メソッド

定義

このアプリケーションの最新バージョンの非同期ダウンロードとインストールを開始します。Starts an asynchronous download and installation of the latest version of this application.

public:
 void UpdateAsync();
public void UpdateAsync ();
member this.UpdateAsync : unit -> unit
Public Sub UpdateAsync ()

例外

ローカル コンピューターは、このアプリケーションが実行するために要求したアクセス許可レベルを付与しませんでした。The local computer did not grant this application the permission level it requested to execute.

ClickOnceClickOnce の配置が破損しています。Your ClickOnceClickOnce deployment is corrupted. 問題の診断および解決方法に関するヒントについては、「ClickOnce 配置のトラブルシューティング」を参照してください。For tips on how to diagnose and correct the problem, see Troubleshooting ClickOnce Deployments.

新しい配置をネットワーク上の場所からダウンロードできませんでした。The new deployment could not be downloaded from its location on the network.

次のコード例では、アプリケーションの読み込み時に新しい更新プログラムを利用できるかどうかを判断します。必要な更新プログラムが利用可能な場合は、更新プログラムが非同期にインストールされます。The following code example determines whether a new update is available at application load time; if a required update is available, it installs the update asynchronously. この例では、 StatusStripコントロールを含む Windows フォームアプリケーションを配置し、このコントロールにという名前ToolStripStatusLabel downloadStatusのコントロールが含まれている必要があります。The example requires that you deploy a Windows Forms application that includes a StatusStrip control, and that this control contain a ToolStripStatusLabel control named downloadStatus.

private:
    long sizeOfUpdate;


private:
    void Form1_Load(Object^ sender, System::EventArgs^ e)
    {
        DoUpdate();
    }

public:
    void DoUpdate()
    {
        if (ApplicationDeployment::IsNetworkDeployed)
        {
            ApplicationDeployment^ currentAppDeployment =
                ApplicationDeployment::CurrentDeployment;
            currentAppDeployment->CheckForUpdateCompleted +=
                gcnew CheckForUpdateCompletedEventHandler(
                this, &Form1::currentDeploy_CheckForUpdateCompleted);
            currentAppDeployment->CheckForUpdateAsync();
        }
    }

    // If update is available, fetch it.
    void currentDeploy_CheckForUpdateCompleted(Object^ sender,
        CheckForUpdateCompletedEventArgs^ e)
    {
        if (nullptr != e->Error)
        {
            // Log error.
            return;
        }

        if (e->UpdateAvailable)
        {
            sizeOfUpdate = (long) e->UpdateSizeBytes;
            if (!e->IsUpdateRequired)
            {
                System::Windows::Forms::DialogResult 
                    updateDialogueResult = MessageBox::Show(
                    "An update is available.Would you like to update the" +
                    " application now?", "Update Available",
                    MessageBoxButtons::OKCancel);
                if (System::Windows::Forms::DialogResult::OK == 
                    updateDialogueResult)
                {
                    BeginUpdate();
                }
            }
            else
            {
                BeginUpdate();
            }
        }
    }

    void BeginUpdate()
    {
        ApplicationDeployment^ ad = ApplicationDeployment::CurrentDeployment;
        ad->UpdateCompleted +=
            gcnew AsyncCompletedEventHandler(
            this, &Form1::CurrentDeployment_UpdateCompleted);

        // Indicate progress in the application's status bar.
        ad->UpdateProgressChanged +=
            gcnew DeploymentProgressChangedEventHandler(this, 
            &Form1::ad_ProgressChanged);

        ad->UpdateAsync();
    }

    void CurrentDeployment_UpdateCompleted(Object^ sender,
        AsyncCompletedEventArgs^ e)
    {
        if (!e->Cancelled)
        {
            if (nullptr != e->Error)
            {
                System::Windows::Forms::DialogResult 
                    restartDialogueResult = MessageBox::Show(
                    "The application has been updated. Restart?",
                    "Restart Application",
                    MessageBoxButtons::OKCancel);
                if (System::Windows::Forms::DialogResult::OK == 
                    restartDialogueResult)
                {
                    Application::Restart();
                }
            }
            else
            {
                // Replace with your own error reporting or logging.
                MessageBox::Show(
                    "The application encountered an error in downloading" +
                    " the latest update. Error: {0}",
                    e->Error->Message);
            }
        }
        else
        {
            // Replace with your own error reporting or logging.
            MessageBox::Show("The update of the application's latest" +
                " version was cancelled.");
        }
    }

    void ad_ProgressChanged(Object^ sender,
        DeploymentProgressChangedEventArgs^ e)
    {
        String^ progressText =
            String::Format(
            "{0:D}K out of {1:D}K downloaded - {2:D}% complete",
            e->BytesCompleted / 1024, e->BytesTotal / 1024,
            e->ProgressPercentage);
        statusStrip1->Text = progressText;
    }
long sizeOfUpdate = 0;

private void UpdateApplication()
{
    if (ApplicationDeployment.IsNetworkDeployed)
    {
        ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
        ad.CheckForUpdateCompleted += new CheckForUpdateCompletedEventHandler(ad_CheckForUpdateCompleted);
        ad.CheckForUpdateProgressChanged += new DeploymentProgressChangedEventHandler(ad_CheckForUpdateProgressChanged);

        ad.CheckForUpdateAsync();
    }
}

void  ad_CheckForUpdateProgressChanged(object sender, DeploymentProgressChangedEventArgs e)
{
    downloadStatus.Text = String.Format("Downloading: {0}. {1:D}K of {2:D}K downloaded.", GetProgressString(e.State), e.BytesCompleted/1024, e.BytesTotal/1024);   
}

string GetProgressString(DeploymentProgressState state)
{
    if (state == DeploymentProgressState.DownloadingApplicationFiles)
    {
        return "application files";
    } 
    else if (state == DeploymentProgressState.DownloadingApplicationInformation) 
    {
        return "application manifest";
    } 
    else 
    {
        return "deployment manifest";
    }
}

void ad_CheckForUpdateCompleted(object sender, CheckForUpdateCompletedEventArgs e)
{
    if (e.Error != null)
    {
        MessageBox.Show("ERROR: Could not retrieve new version of the application. Reason: \n" + e.Error.Message + "\nPlease report this error to the system administrator.");
        return;
    }
    else if (e.Cancelled == true)
    {
        MessageBox.Show("The update was cancelled.");
    }

    // Ask the user if they would like to update the application now.
    if (e.UpdateAvailable)
    {
        sizeOfUpdate = e.UpdateSizeBytes;

        if (!e.IsUpdateRequired)
        {
            DialogResult dr = MessageBox.Show("An update is available. Would you like to update the application now?\n\nEstimated Download Time: ", "Update Available", MessageBoxButtons.OKCancel);
            if (DialogResult.OK == dr)
            {
                BeginUpdate();
            }
        }
        else
        {
            MessageBox.Show("A mandatory update is available for your application. We will install the update now, after which we will save all of your in-progress data and restart your application.");
            BeginUpdate();
        }
    }
}

private void BeginUpdate()
{
    ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
    ad.UpdateCompleted += new AsyncCompletedEventHandler(ad_UpdateCompleted);

    // Indicate progress in the application's status bar.
    ad.UpdateProgressChanged += new DeploymentProgressChangedEventHandler(ad_UpdateProgressChanged);
    ad.UpdateAsync();
}

void ad_UpdateProgressChanged(object sender, DeploymentProgressChangedEventArgs e)
{
    String progressText = String.Format("{0:D}K out of {1:D}K downloaded - {2:D}% complete", e.BytesCompleted / 1024, e.BytesTotal / 1024, e.ProgressPercentage);
    downloadStatus.Text = progressText;
}

void ad_UpdateCompleted(object sender, AsyncCompletedEventArgs e)
{
    if (e.Cancelled)
    {
        MessageBox.Show("The update of the application's latest version was cancelled.");
        return;
    }
    else if (e.Error != null)
    {
        MessageBox.Show("ERROR: Could not install the latest version of the application. Reason: \n" + e.Error.Message + "\nPlease report this error to the system administrator.");
        return;
    }

    DialogResult dr = MessageBox.Show("The application has been updated. Restart? (If you do not restart now, the new version will not take effect until after you quit and launch the application again.)", "Restart Application", MessageBoxButtons.OKCancel);
    if (DialogResult.OK == dr)
    {
        Application.Restart();
    }
}
Private sizeOfUpdate As Long = 0

Dim WithEvents ADUpdateAsync As ApplicationDeployment

Private Sub UpdateApplication()
    If (ApplicationDeployment.IsNetworkDeployed) Then
        ADUpdateAsync = ApplicationDeployment.CurrentDeployment

        ADUpdateAsync.CheckForUpdateAsync()
    End If
End Sub

Private Sub ADUpdateAsync_CheckForUpdateProgressChanged(ByVal sender As Object, ByVal e As DeploymentProgressChangedEventArgs) Handles ADUpdateAsync.CheckForUpdateProgressChanged
    DownloadStatus.Text = [String].Format("{0:D}K of {1:D}K downloaded.", e.BytesCompleted / 1024, e.BytesTotal / 1024)
End Sub


Private Sub ADUpdateAsync_CheckForUpdateCompleted(ByVal sender As Object, ByVal e As CheckForUpdateCompletedEventArgs) Handles ADUpdateAsync.CheckForUpdateCompleted
    If (e.Error IsNot Nothing) Then
        MessageBox.Show(("ERROR: Could not retrieve new version of the application. Reason: " + ControlChars.Lf + e.Error.Message + ControlChars.Lf + "Please report this error to the system administrator."))
        Return
    Else
        If (e.Cancelled = True) Then
            MessageBox.Show("The update was cancelled.")
        End If
    End If

    ' Ask the user if they would like to update the application now.
    If (e.UpdateAvailable) Then
        sizeOfUpdate = e.UpdateSizeBytes

        If (Not e.IsUpdateRequired) Then
            Dim dr As DialogResult = MessageBox.Show("An update is available. Would you like to update the application now?", "Update Available", MessageBoxButtons.OKCancel)
            If (System.Windows.Forms.DialogResult.OK = dr) Then
                BeginUpdate()
            End If
        Else
            MessageBox.Show("A mandatory update is available for your application. We will install the update now, after which we will save all of your in-progress data and restart your application.")
            BeginUpdate()
        End If
    End If
End Sub

Private Sub BeginUpdate()
    ADUpdateAsync = ApplicationDeployment.CurrentDeployment
    ADUpdateAsync.UpdateAsync()
End Sub


Private Sub ADUpdateAsync_UpdateProgressChanged(ByVal sender As Object, ByVal e As DeploymentProgressChangedEventArgs) Handles ADUpdateAsync.UpdateProgressChanged
    Dim progressText As String = String.Format("{0:D}K out of {1:D}K downloaded - {2:D}% complete", e.BytesCompleted / 1024, e.BytesTotal / 1024, e.ProgressPercentage)
    DownloadStatus.Text = progressText
End Sub


Private Sub ADUpdateAsync_UpdateCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs) Handles ADUpdateAsync.UpdateCompleted
    If (e.Cancelled) Then
        MessageBox.Show("The update of the application's latest version was cancelled.")
        Exit Sub
    Else
        If (e.Error IsNot Nothing) Then
            MessageBox.Show("ERROR: Could not install the latest version of the application. Reason: " + ControlChars.Lf + e.Error.Message + ControlChars.Lf + "Please report this error to the system administrator.")
            Exit Sub
        End If
    End If

    Dim dr As DialogResult = MessageBox.Show("The application has been updated. Restart? (If you do not restart now, the new version will not take effect until after you quit and launch the application again.)", "Restart Application", MessageBoxButtons.OKCancel)
    If (dr = System.Windows.Forms.DialogResult.OK) Then
        Application.Restart()
    End If
End Sub

注釈

によってUpdateLocation指定された場所にアプリケーションの新しいバージョンを発行し、アプリケーションの配置マニフェストのバージョン番号が現在のアプリケーションのバージョン番号よりも大きい場合、アプリケーションは更新されたと見なされます。ユーザーのコンピューターにインストールされます。An application is considered updated when you publish a new version of the application to the location specified by UpdateLocation, and the version number in the application's deployment manifest is greater than the version number of the application currently installed on the user's computer.

更新プログラムのダウンロード中ClickOnceClickOnceに、はUpdateProgressChangedメインアプリケーションスレッドでイベントハンドラーを生成して、ダウンロードの状態を通知します。While downloading the update, ClickOnceClickOnce will raise the UpdateProgressChanged event handler on the main application thread to inform you of the status of the download. 非同期更新が完了するか、例外が発生ClickOnceClickOnceすると、 UpdateCompletedはメインアプリケーションスレッドでイベントを発生させます。When the asynchronous update finishes or encounters an exception, ClickOnceClickOnce will raise the UpdateCompleted event on the main application thread. このイベントAsyncCompletedEventArgsに提供されたを調べて、更新が成功したかどうかを確認します。Examine the AsyncCompletedEventArgs supplied to this event to determine whether the update succeeded.

UpdateAsync例外をスローしClickOnceClickOnceUpdateCompleted場合、はErrorを呼び出しAsyncCompletedEventArgs 、のプロパティをスローされた例外に設定します。If UpdateAsync throws an exception, ClickOnceClickOnce calls UpdateCompleted and sets the Error property of AsyncCompletedEventArgs to the exception that was thrown.

UpdateAsyncは、アプリケーションマニフェストで "optional" とマークされていない展開内のすべてのファイルをダウンロードします。UpdateAsync will download all files in a deployment not marked as "optional" in the application manifest. 必要に応じて、 DownloadFileGroup DownloadFileGroupAsyncまたはメソッドを使用して、オプションのファイルをダウンロードできます。You can download optional files on demand by using the DownloadFileGroup or the DownloadFileGroupAsync method.

ClickOnceClickOnceは、 UpdateAsyncメソッドを呼び出したときに、アプリケーションを自動的に更新している場合があります。この場合InvalidOperationException、このメソッドを呼び出すと、がスローされます。may already be updating the application automatically when you call the UpdateAsync method; if that happens, calls to this method will throw an InvalidOperationException.

配置内の1つ以上のファイルを更新しても、アプリケーションマニフェストを更新していない場合は、 InvalidDeploymentExceptionが表示されます。If you have updated one or more files in your deployment, but you have not refreshed your application manifest, you will receive an InvalidDeploymentException. ほとんどの場合、アプリケーションマニフェストを再構築すると、この問題が解決されます。Most of the time, rebuilding your application manifest solves this problem. また、配置マニフェストまたはアプリケーションマニフェストの公開キーの署名が無効であるか、見つからない場合にも、この例外が発生します。You will also receive this exception if a public-key signature on a deployment manifest or application manifest is invalid or missing.

更新プログラムによって、以前のバージョンのアプリケーションよりも高いレベルの信頼がローカルコンピューターに要求される場合があります。An update may request a higher level of trust on the local computer than the previous version of the application. アプリケーションが信頼されたアプリケーションの配置を使用する場合、共通言語ランタイム (CLR) 信頼マネージャーは、配置マニフェストを調べて、有効な信頼ライセンスが含まれているかどうかを判断します。If the application uses Trusted Application Deployment, the common language runtime (CLR) trust manager examines the deployment manifest to determine whether it contains a valid trust license. 配置マニフェストに有効な信頼ライセンスが含まれていClickOnceClickOnceない場合、はインストールをTrustNotGrantedException停止し、をスローします。If the deployment manifest does not contain a valid trust license, ClickOnceClickOnce stops the installation and throws a TrustNotGrantedException. UpdateAsyncでは、実行するアクセス許可をアプリケーションに付与するかどうかを確認するプロンプトが表示されません。UpdateAsync will never display a prompt asking the user if they want to grant the application permission to run.

セキュリティ

PermissionSet
ローカルコンピューターへのフルアクセス。For full access to the local computer. PermissionState (関連する列挙体)Associated enumeration: PermissionState.

適用対象

こちらもご覧ください