You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测当前C#/WPF应用是否通过MSIX包启动运行

MSIX运行状态判断最优方案

方案1:调用Win32 API判断(推荐,无异常开销,兼容性最好)

这是Windows原生提供的判断逻辑,不会产生异常开销,兼容所有支持MSIX部署的Windows版本(Windows 10 1709+),不需要额外引用WinRT相关程序集,.NET Framework、.NET Core/.NET 5+ 项目都可以直接使用:

using System.Runtime.InteropServices;

public static class DeploymentHelper
{
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern int GetCurrentPackageId(ref int bufferLength, byte[] buffer);

    private const int APPMODEL_ERROR_NO_PACKAGE = 15700;

    /// <summary>
    /// 判断当前程序是否从MSIX包中运行,效果等价于ClickOnce场景下的 `ApplicationDeployment.IsNetworkDeployed`
    /// </summary>
    public static bool IsRunningAsMsix()
    {
        int bufferLength = 0;
        int result = GetCurrentPackageId(ref bufferLength, null);
        // 返回15700错误码说明当前进程没有包身份,不是从MSIX运行
        return result != APPMODEL_ERROR_NO_PACKAGE;
    }
}

方案2:优化后的异常捕获方案(适合不想引入Win32 API声明的场景)

你当前的try catch方案可以优化,不需要访问DisplayName属性,直接判断Package.Current是否存在,同时仅捕获特定异常,减少不必要的性能损耗:

using Windows.ApplicationModel;

public static class DeploymentHelper
{
    public static bool IsRunningAsMsix()
    {
        try
        {
            return Package.Current != null;
        }
        // 无包身份时访问Package.Current会固定抛出FileNotFoundException
        catch (FileNotFoundException)
        {
            return false;
        }
    }
}

注意:该方案需要你的项目引用了Windows SDK相关程序集,适合目标框架为netX.0-windows的.NET Core/.NET 5+项目使用。

内容的提问来源于stack exchange,提问作者peterlustig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 10:15:07