简体   繁体   English

如何获取存储在部署项目中的产品版本号?

[英]How to get the product Version number which is stored in the Deployment Project?

I have a WinForms application written in C#. 我有一个用C#编写的WinForms应用程序。 There is a Deployment Project which creates a setup.exe and where I set a version number. 有一个部署项目可创建setup.exe,并在其中设置版本号。

How can I fetch this version number at runtime so that I can write it to a log or display it in the About box? 如何在运行时获取此版本号,以便可以将其写入日志或在“关于”框中显示它?

I had been using the following code but it does not work for 64-bit installations. 我一直在使用以下代码,但不适用于64位安装。

RegistryKey key = Registry.LocalMachine.OpenSubKey(
        @"Software\Microsoft\Windows\CurrentVersion\Uninstall");
string[] subKeyNames = key.GetSubKeyNames();

foreach (string subKeyName in subKeyNames)
{
    Microsoft.Win32.RegistryKey subKey2 = key.OpenSubKey(subKeyName);

    if (ValueNameExists(subKey2.GetValueNames(), "DisplayName") 
        && ValueNameExists(subKey2.GetValueNames(), "DisplayVersion"))
    {
        string name = subKey2.GetValue("DisplayName").ToString();
        string version = subKey2.GetValue("DisplayVersion").ToString();
        if(name == "MyAppName") return version;
    }
    subKey2.Close();
}
key.Close();
return "v?";

you can try this : 你可以试试这个:

string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(registry_key))
{
    foreach (string subkey_name in key.GetSubKeyNames())
    {
        using (Microsoft.Win32.RegistryKey subkey = key.OpenSubKey(subkey_name))
        {
            if (!object.ReferenceEquals(subkey.GetValue("DisplayName"), null))
            {
                string[] str = subkey.GetValueNames();
                string SoftNames = Convert.ToString(subkey.GetValue("DisplayName"));
                if (SoftNames == "MyAppName")
                {
                    string Vendor_Publisher = Convert.ToString(subkey.GetValue("Publisher"));
                    string Version = Convert.ToString(subkey.GetValue("DisplayVersion"));
                    string InstallDate = FormatDateTime(subkey.GetValue("InstallDate"));
                }

            }
        }
    }
}



private static string FormatDateTime(object ObjInstallDate)
{
    object FinalDate = DBNull.Value;
    string strDate = Convert.ToString(ObjInstallDate);
    DateTime dtm;
    DateTime.TryParseExact(strDate, new string[] { "yyyyMMdd", "yyyy-MM-dd", "dd-MM-yyyy" }, 
        System.Globalization.CultureInfo.InvariantCulture,
        System.Globalization.DateTimeStyles.None, out dtm);
    if (!String.IsNullOrEmpty(strDate))
    {                
        FinalDate = dtm;
    }
    return FinalDate.ToString();
}

如果只想在应用程序的“关于”框中显示应用程序版本,则可以从static属性获取当前版本,如下所示:

My.Application.Info.Version

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM