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

.NET Core 6 C#应用如何获取Visual Studio中的版本?(附旧版方法)

在.NET Core 6中获取Visual Studio设置的应用版本

下面针对不同场景提供对应的实现方案:

一、普通.NET Core 6应用(非ClickOnce部署)

如果你的应用不是通过ClickOnce发布,而是常规的exe/dll部署,可以直接从程序集信息中读取版本,这对应Visual Studio里项目属性→应用程序→程序集信息(或.csproj文件中Version节点)设置的版本值。

代码示例

控制台/桌面应用(顶级语句写法)

using System.Reflection;

var assembly = Assembly.GetEntryAssembly();
var version = assembly.GetName().Version;
var versionStr = $"v{version.Major}.{version.Minor}.{version.Revision}";
Console.WriteLine(versionStr);

类库或非顶级语句场景

using System.Reflection;

public string GetAppVersion()
{
    var assembly = Assembly.GetExecutingAssembly();
    var version = assembly.GetName().Version;
    return $"v{version.Major}.{version.Minor}.{version.Revision}";
}

补充说明

  • 如果需要读取文件版本(对应程序集信息里的“文件版本”字段),可以用以下方式:
var fileVersionInfo = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location);
var fileVersionStr = $"v{fileVersionInfo.FileMajorPart}.{fileVersionInfo.FileMinorPart}.{fileVersionInfo.FileBuildPart}";
  • 也可以直接在.csproj文件中显式配置版本,示例:
<PropertyGroup>
  <Version>1.2.3</Version>
  <FileVersion>1.2.3.0</FileVersion>
</PropertyGroup>

二、ClickOnce部署的.NET Core 6应用

如果你的.NET Core 6应用是通过ClickOnce发布(Visual Studio 2019及以上版本支持),可以沿用类似.NET Framework的方式,需确保项目已启用ClickOnce部署,并添加必要引用。

代码示例

using System.Deployment.Application;
using System.Reflection;

public string GetAppVersion()
{
    if (ApplicationDeployment.IsNetworkDeployed)
    {
        var currentAppDeploy = ApplicationDeployment.CurrentDeployment;
        return $"v{currentAppDeploy.CurrentVersion.Major}.{currentAppDeploy.CurrentVersion.Minor}.{currentAppDeploy.CurrentVersion.Revision}";
    }
    // 非ClickOnce部署时的 fallback 逻辑
    var assembly = Assembly.GetEntryAssembly();
    var version = assembly.GetName().Version;
    return $"v{version.Major}.{version.Minor}.{version.Revision}";
}

注意事项

  • 启用ClickOnce部署后,Visual Studio会自动管理版本号,可在发布设置中配置版本递增规则。
  • 若编译时提示找不到System.Deployment.Application,需在项目中通过NuGet安装Microsoft.Windows.Compatibility包。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 20:05:46