Use C# to interact with Windows Update

DevinB picture DevinB · May 28, 2009 · Viewed 35.5k times · Source

Is there any API for writing a C# program that could interface with Windows update, and use it to selectively install certain updates?

I'm thinking somewhere along the lines of storing a list in a central repository of approved updates. Then the client side applications (which would have to be installed once) would interface with Windows Update to determine what updates are available, then install the ones that are on the approved list. That way the updates are still applied automatically from a client-side perspective, but I can select which updates are being applied.

This is not my role in the company by the way, I was really just wondering if there is an API for windows update and how to use it.

Answer

Add a Reference to WUApiLib to your C# project.

using WUApiLib;
protected override void OnLoad(EventArgs e){
    base.OnLoad(e);
    UpdateSession uSession = new UpdateSession();
    IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher();
    uSearcher.Online = false;
    try {
        ISearchResult sResult = uSearcher.Search("IsInstalled=1 And IsHidden=0");
        textBox1.Text = "Found " + sResult.Updates.Count + " updates" + Environment.NewLine;
        foreach (IUpdate update in sResult.Updates) {
                textBox1.AppendText(update.Title + Environment.NewLine);
        }
    }
    catch (Exception ex) {
        Console.WriteLine("Something went wrong: " + ex.Message);
    }
}

Given you have a form with a TextBox this will give you a list of the currently installed updates. See http://msdn.microsoft.com/en-us/library/aa387102(VS.85).aspx for more documentation.

This will, however, not allow you to find KB hotfixes which are not distributed via Windows Update.