c# - 单击 setup.exe 时无法获取应用程序启动路径

标签 c# .net winforms

我正在发布一个 Windows 项目,单击表单后我正在安装另一个安装程序。

我没有在按钮上的 clickevent 上获取当前应用程序启动路径。

在调试和发布时它显示正确的路径,但在发布后它给出

C:\Users\username\AppData\Local\Apps\2.0 path

我已经用过:

Application.StartupPath
Application.Executablepath
Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location))
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase))
Path.Combine(Directory.GetCurrentDirectory())

但总是显示没有用

C:\Users\username\AppData\Local\Apps\2.0 path

最佳答案

您获得该路径是因为它是 ClickOnce 使用的路径。 ClickOnce 应用程序安装在安装它们的用户的配置文件下。

编辑:

方法一:

这是获取应用程序安装路径的方法(仅在安装了应用程序时才有效)(其中部分内容由 @codeConcussion 编写):

// productName is name you assigned to your app in the 
// Project properties -> Publish -> Publish Settings
public static string GetInstalledFromDir(string productName)
{
    using (var key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall"))
    {
        if (key != null)
        {
            var appKey = key.GetSubKeyNames().FirstOrDefault(x => GetValue(key, x, "DisplayName") == productName);
            return appKey == null ? null : GetValue(key, appKey, "UrlUpdateInfo");
        }
    }

    return null;
}

private static string GetValue(RegistryKey key, string app, string value)
{
    using (var subKey = key.OpenSubKey(app))
    {
        if (subKey == null || !subKey.GetValueNames().Contains(value)) 
        { 
            return null; 
        }

        return subKey.GetValue(value).ToString();
    }
}

使用方法如下:

Uri uri = new Uri(GetInstalledFromDir("ProductName"));
MessageBox.Show(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)));

方法2:

你也可以尝试

System.Deployment.Application.ApplicationDeployment.CurrentDeployment.ActivationUri

但我认为只有当您的应用程序是从互联网安装时此功能才有效

关于c# - 单击 setup.exe 时无法获取应用程序启动路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12795813/

相关文章:

c# - 在全局级别抑制 StyleCop 警告

c# - 如何通过 webAPI 传递\用户 azure continue token

.net - 在构建时将项目引用更改为 NuGet 包引用

c# - 如何设置对.NET X.509 证书私钥文件的读取权限

c# - 应用程序域和线程

c# - 如何在没有 yield 语句的情况下实现迭代器模式 (IEnumerator<T>)

.net - 在 Powershell 中使用升级的 FolderBrowserDialog ("Vista style")

winforms - 根据与远边缘不同的约束来调整无边界形式的大小?

与 Font 类的 Style 属性一起使用的 C# 技术

c# - Windows Phone 中的命令参数等效?