Skip to main content

Prerequisites

  • Windows 10/11 - Windows Package Manager requires Windows 10 1809 or later
  • WinGet Installed - Install from Microsoft Store or GitHub releases
  • Development Tools:
    • Visual Studio 2019/2022 (for C++/C#)
    • .NET 6.0 SDK or later (for C#)
    • Windows SDK 10.0.22621.0 or later

Installation

For C# Development

1

Create a new project

Create a .NET Console Application or Windows App SDK project:
dotnet new console -n WinGetComExample
cd WinGetComExample
2

Add Windows SDK reference

Edit your .csproj file to add the Windows SDK:
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
    <Platforms>x64;ARM64</Platforms>
    <RuntimeIdentifiers>win-x64;win-arm64</RuntimeIdentifiers>
    <TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
  </PropertyGroup>
</Project>
3

Add using directives

Add the necessary namespaces:
using Microsoft.Management.Deployment;
using Windows.Foundation;
using Windows.Foundation.Collections;

For C++ Development

1

Create C++/WinRT project

Create a new Windows Console Application with C++/WinRT support in Visual Studio.
2

Add includes

Include the COM API headers:
#include <winrt/Microsoft.Management.Deployment.h>
#include <winrt/Microsoft.Management.Configuration.h>
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>
3

Add namespace aliases

namespace winrt {
    using namespace Microsoft::Management::Deployment;
    using namespace Microsoft::Management::Configuration;
    using namespace Windows::Foundation;
    using namespace Windows::Foundation::Collections;
}

Basic Examples

Example 1: List Available Catalogs

using Microsoft.Management.Deployment;

class Program
{
    static void Main()
    {
        var manager = new PackageManager();
        var catalogs = manager.GetPackageCatalogs();
        
        Console.WriteLine("Available Package Catalogs:");
        foreach (var catalogRef in catalogs)
        {
            if (!catalogRef.IsComposite)
            {
                var info = catalogRef.Info;
                Console.WriteLine($"- {info.Name} ({info.Type})");
                Console.WriteLine($"  Origin: {info.Origin}");
                Console.WriteLine($"  Trust Level: {info.TrustLevel}");
            }
        }
    }
}

Example 2: Search for a Package

using Microsoft.Management.Deployment;

async Task SearchPackageAsync(string packageId)
{
    var manager = new PackageManager();
    
    // Get the winget catalog
    var catalogRef = manager.GetPredefinedPackageCatalog(
        PredefinedPackageCatalog.OpenWindowsCatalog
    );
    
    // Connect to catalog
    var connectResult = await catalogRef.ConnectAsync();
    if (connectResult.Status != ConnectResultStatus.Ok)
    {
        Console.WriteLine($"Failed to connect: {connectResult.Status}");
        return;
    }
    
    // Create search filter
    var options = new FindPackagesOptions();
    var filter = new PackageMatchFilter()
    {
        Field = PackageMatchField.Id,
        Value = packageId,
        Option = PackageFieldMatchOption.ContainsCaseInsensitive
    };
    options.Selectors.Add(filter);
    
    // Search
    var findResult = await connectResult.PackageCatalog.FindPackagesAsync(options);
    
    if (findResult.Status == FindPackagesResultStatus.Ok)
    {
        Console.WriteLine($"Found {findResult.Matches.Count} packages:");
        foreach (var match in findResult.Matches)
        {
            var package = match.CatalogPackage;
            Console.WriteLine($"- {package.Id}: {package.Name}");
            Console.WriteLine($"  Version: {package.DefaultInstallVersion.Version}");
        }
    }
}

Example 3: Install a Package

using Microsoft.Management.Deployment;

async Task InstallPackageAsync(string packageId)
{
    var manager = new PackageManager();
    
    // Search for package (see Example 2)
    var catalogRef = manager.GetPredefinedPackageCatalog(
        PredefinedPackageCatalog.OpenWindowsCatalog
    );
    var connectResult = await catalogRef.ConnectAsync();
    
    var options = new FindPackagesOptions();
    options.Selectors.Add(new PackageMatchFilter() 
    {
        Field = PackageMatchField.Id,
        Value = packageId,
        Option = PackageFieldMatchOption.Equals
    });
    
    var findResult = await connectResult.PackageCatalog.FindPackagesAsync(options);
    
    if (findResult.Matches.Count == 0)
    {
        Console.WriteLine("Package not found");
        return;
    }
    
    var package = findResult.Matches[0].CatalogPackage;
    
    // Install the package
    var installOptions = new InstallOptions()
    {
        PackageInstallMode = PackageInstallMode.Silent,
        AcceptPackageAgreements = true
    };
    
    var installOperation = manager.InstallPackageAsync(package, installOptions);
    
    // Track progress
    installOperation.Progress = (operation, progress) =>
    {
        Console.WriteLine($"State: {progress.State}");
        if (progress.DownloadProgress > 0)
        {
            Console.WriteLine($"Download: {progress.DownloadProgress * 100:F1}%");
        }
    };
    
    var installResult = await installOperation;
    
    if (installResult.Status == InstallResultStatus.Ok)
    {
        Console.WriteLine("Installation successful!");
    }
    else
    {
        Console.WriteLine($"Installation failed: {installResult.Status}");
        Console.WriteLine($"Error: 0x{installResult.ExtendedErrorCode:X}");
    }
}

Configuration Example

using Microsoft.Management.Configuration;
using Windows.Storage;

async Task ApplyConfigurationAsync(string configPath)
{
    // Create configuration processor factory
    var factory = await ConfigurationStaticFunctions
        .CreateConfigurationSetProcessorFactoryAsync("pwsh");
    
    var processor = new ConfigurationProcessor(factory);
    
    // Open configuration file
    var file = await StorageFile.GetFileFromPathAsync(configPath);
    var stream = await file.OpenReadAsync();
    var openResult = await processor.OpenConfigurationSetAsync(stream);
    
    if (openResult.ResultCode != 0)
    {
        Console.WriteLine($"Failed to open: 0x{openResult.ResultCode:X}");
        Console.WriteLine($"Field: {openResult.Field}, Line: {openResult.Line}");
        return;
    }
    
    var configSet = openResult.Set;
    Console.WriteLine($"Configuration: {configSet.Name}");
    Console.WriteLine($"Units: {configSet.Units.Count}");
    
    // Apply configuration
    var applyOperation = processor.ApplySetAsync(
        configSet, 
        ApplyConfigurationSetFlags.None
    );
    
    applyOperation.Progress = (operation, data) =>
    {
        if (data.Change == ConfigurationSetChangeEventType.UnitStateChanged)
        {
            Console.WriteLine($"Unit: {data.Unit.Type} - {data.UnitState}");
        }
    };
    
    var applyResult = await applyOperation;
    Console.WriteLine($"Result: 0x{applyResult.ResultCode:X}");
}

Common Patterns

Error Handling

Always check result status codes:
if (result.Status != InstallResultStatus.Ok)
{
    Console.WriteLine($"Operation failed: {result.Status}");
    Console.WriteLine($"HRESULT: 0x{result.ExtendedErrorCode:X8}");
    
    if (result.Status == InstallResultStatus.InstallError)
    {
        Console.WriteLine($"Installer Error Code: {result.InstallerErrorCode}");
    }
}

Async/Await Pattern

Most operations are asynchronous:
// Use async version for UI applications
var result = await manager.InstallPackageAsync(package, options);

// Or synchronous for console apps (blocks thread)
var result = manager.InstallPackageAsync(package, options).GetAwaiter().GetResult();

Progress Tracking

Monitor long-running operations:
var operation = manager.InstallPackageAsync(package, options);
operation.Progress = (op, progress) =>
{
    // Update UI or log progress
    UpdateProgressBar(progress.DownloadProgress);
};
var result = await operation;

Next Steps

PackageManager API

Learn about package operations

Configuration API

Work with configuration sets

Error Handling

Handle errors effectively

Events & Progress

Track operation progress

Troubleshooting

Common Issues

“Class not registered” error
  • Ensure Windows Package Manager is installed
  • Verify your app targets the correct Windows SDK version
  • Check that WinGet is available at runtime
Access denied errors
  • Some operations require administrator privileges
  • Declare runFullTrust capability in your app manifest
Package not found
  • Ensure catalog is connected before searching
  • Check catalog name and package ID spelling
  • Verify catalog sources are configured correctly

Build docs developers (and LLMs) love