我希望能够显示使用发布向导部署的.NET应用程序的当前版本。有一个不错的选项,可以在每次发布应用程序时自动更新版本号。
我发现了另一个问题 (Automatically update version number),其中提到了获取当前版本的方法:
Assembly.GetExecutingAssembly().GetName().Version
这会获取您在项目属性中设置的版本,但不会获取每次发布时自动递增的版本。
我希望能够显示使用发布向导部署的.NET应用程序的当前版本。有一个不错的选项,可以在每次发布应用程序时自动更新版本号。
我发现了另一个问题 (Automatically update version number),其中提到了获取当前版本的方法:
Assembly.GetExecutingAssembly().GetName().Version
这会获取您在项目属性中设置的版本,但不会获取每次发布时自动递增的版本。
您可以使用以下测试
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed) {
return System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion;
}
为了避免异常情况(详见此帖)。
另外,我认为你不能通过Visual Studio调试来获取当前的发布版本,因为访问CurrentDeployment
将引发InvalidDeploymentException
异常。
我最终使用了这段小代码来获取当前已部署的版本或者如果没有部署,则获取当前程序集版本。
private Version GetRunningVersion()
{
try
{
return Application.ApplicationDeployment.CurrentDeployment.CurrentVersion;
}
catch
{
return Assembly.GetExecutingAssembly().GetName().Version;
}
}
我不得不添加对System.Deployment
和System.Reflection
的引用。
DataSet ds = new DataSet();
ds.ReadXml(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MyProd.application"));
DataTable dt = new DataTable();
if (ds.Tables.Count > 1) {
dt = ds.Tables[1];
MessageBox.Show(dt.Rows[0]["version"].ToString());
}
根据Jason的回答,我得到了以下内容:
添加对System.Deployment的引用。
string versionDeploy = Application.ProductVersion;
if (System.Diagnostics.Debugger.IsAttached)
{
this.lblVersion.Caption = string.Format("Versión {0} DESA", versionDeploy);
}
else
{
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
{
Version Deploy = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion;
versionDeploy = string.Format("{0}.{1}.{2}.{3}", Deploy.Major, Deploy.Minor, Deploy.Build, Deploy.Revision);
}
this.lblVersion.Caption = string.Format("Versión {0} PROD", versionDeploy);
}
using System.Deployment.Application;
并且
string yourPublishedVersionNumber=ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString()
ApplicationDeployment.IsNetworkDeployed
,否则 ApplicationDeployment.CurrentDeployment
会抛出异常。 - Michal CiechanImports System.Configuration
Public Function GetAppVersion() As String
Dim ass As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()
Dim ver As System.Version = ass.GetName().Version
Return ver.Major & "." & ver.Minor & "." & ver.Revision
End Function