我正在开发桌面应用程序,已经创建了一个安装包。
例如:我的应用程序版本是1.0.0。
我想获取当前桌面应用程序的版本,即1.0.0
。我尝试使用Application.ProductVersion
,但它只提供了控件的版本信息。(我使用的是DevExpress Control
15.2.7,所以它提供的当前版本是15.2.7
)
如何获取已安装应用程序的当前版本?我想将其与已安装版本进行比较,以为我的产品提供“新版本可用”功能。
我正在开发桌面应用程序,已经创建了一个安装包。
例如:我的应用程序版本是1.0.0。
我想获取当前桌面应用程序的版本,即1.0.0
。我尝试使用Application.ProductVersion
,但它只提供了控件的版本信息。(我使用的是DevExpress Control
15.2.7,所以它提供的当前版本是15.2.7
)
如何获取已安装应用程序的当前版本?我想将其与已安装版本进行比较,以为我的产品提供“新版本可用”功能。
你需要寻找的信息位于AssemblyInfo.cs中。
在运行时,您可以使用System.Reflection.Assembly
来访问在其中编写的信息。
使用System.Reflection.Assembly.GetExecutingAssembly()
获取程序集(包含此行代码的程序集),或者使用System.Reflection.Assembly.GetEntryAssembly()
获取启动项目的程序集(通常是您的应用程序)。
在多项目解决方案中,这是需要注意的事情!
string version = Assembly.GetExecutingAssembly().GetName().Version.ToString()
// returns 1.0.0.0
对应的AssemblyInfo.cs文件:
对应的EXE属性:
GetEntryAssembly
而不是GetExecutingAssembly
进行操作。 - Felix D.System.Reflection.Assembly executingAssembly = System.Reflection.Assembly.GetExecutingAssembly();
var fieVersionInfo = FileVersionInfo.GetVersionInfo(executingAssembly .Location);
var version = fieVersionInfo.FileVersion;
另一种方法基本上与已接受的答案相同,即:
Version appVersion = Assembly.GetExecutingAssembly().GetName().Version;
versionLabel.Text = "v" + appVersion.Major + "." + appVersion.Minor + "." + appVersion.Build + ".";
获取特定程序集的版本:
private const string AssemblyName = "MyAssembly"; // Name of your assembly
public Version GetVersion()
{
// Get all the assemblies currently loaded in the application domain.
Assembly[] assemblies = Thread.GetDomain().GetAssemblies();
for (int i = 0; i < assemblies.Length; i++)
{
if (string.Compare(assemblies[i].GetName().Name, AssemblyName) == 0)
{
return assemblies[i].GetName().Version;
}
}
return Assembly.GetExecutingAssembly().GetName().Version; // return current version assembly or return null;
}
Assembly.GetEntryAssembly()
,在 Visual Studio 调试和独立运行时都能正常工作,但当 XAML 设计器加载时,它会返回当前 Visual Studio 版本(或某个组件的版本)。这个解决方案在所有三种情况下都有效 :D - Clonkexthis.Text = this.Text + " " + Application.ProductVersion;
如果您正在使用Windows窗体应用程序,您可以仅使用ProductVersion
。
// Set form text. This is showing upper the form titel bar
this.Text = "Application name" + ProductVersion;
this.Text = "My Awesome App";
//Get Version
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
{
Version ver = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion;
this.Text += string.Format(" v{0}.{1}", ver.Major, ver.Revision, Assembly.GetEntryAssembly().GetName().Name);
}
else
{
var ver = Assembly.GetExecutingAssembly().GetName().Version;
this.Text += string.Format(" v{0}.{1}", ver.Major, ver.Revision, Assembly.GetEntryAssembly().GetName().Name);
}