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

如何在C#中获取.NET v4.5.2程序的安装路径?

获取.NET 4.5.2程序安装目录的正确方法

以下是两种可靠的方式获取程序安装文件夹路径,从而定位到你的脚本:

  • 方法1:使用AppDomain.CurrentDomain.BaseDirectory
    这是桌面应用(WinForms/控制台)最常用的方式,直接返回应用程序域的基目录,也就是安装目录,不受调试或影子复制影响。
    代码示例:

    string installDir = AppDomain.CurrentDomain.BaseDirectory;
    // 拼接脚本路径,替换成你的脚本文件名
    string scriptPath = Path.Combine(installDir, "your-script-file.ext");
    
  • 方法2:使用程序集路径
    通过获取当前执行程序集的物理路径,再提取目录。如果你的程序存在影子复制场景(比如某些插件或特殊部署),可以用GetEntryAssembly()代替GetExecutingAssembly(),确保拿到主程序的安装路径。
    代码示例:

    // 获取主程序集的路径
    string assemblyPath = Assembly.GetEntryAssembly().Location;
    string installDir = Path.GetDirectoryName(assemblyPath);
    string scriptPath = Path.Combine(installDir, "your-script-file.ext");
    

为什么之前的方法不行?

  • Environment.SpecialFolder.ApplicationData本来就是用户的漫游数据目录(用来存用户配置、缓存),和程序安装目录完全是两个位置,所以用错了场景。
  • Environment.GetCommandLineArgs()[0]在VS调试时会指向项目的bin目录,但发布安装后应该会返回正确路径,不过不如上面两种方法稳定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 02:55:39